absiitr commited on
Commit
dcf3a0f
·
verified ·
1 Parent(s): 8f9140b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +131 -251
app.py CHANGED
@@ -3,168 +3,107 @@ import tempfile
3
  import gc
4
  import logging
5
  import streamlit as st
6
- from groq import Groq, APIError
7
  from langchain_community.document_loaders import PyPDFLoader
8
  from langchain_text_splitters import RecursiveCharacterTextSplitter
9
  from langchain_community.embeddings import HuggingFaceEmbeddings
10
  from langchain_community.vectorstores import Chroma
11
  import torch
12
 
13
- # ---------------- CONFIGURATION ----------------
 
14
  logging.basicConfig(level=logging.INFO)
15
 
16
- # Load API key from Hugging Face secrets
17
  GROQ_API_KEY = st.secrets.get("GROQ_API_KEY", os.environ.get("GROQ_API_KEY"))
18
  GROQ_MODEL = "llama-3.1-8b-instant"
19
 
20
- # Initialize Groq client
21
- client = None
22
- if GROQ_API_KEY:
23
- try:
24
- client = Groq(api_key=GROQ_API_KEY)
25
- logging.info("✅ Groq client initialized successfully.")
26
- except Exception as e:
27
- st.error(f"❌ Failed to initialize Groq client: {e}")
28
- client = None
29
- else:
30
- st.warning("⚠️ GROQ_API_KEY not found. Please add it to Hugging Face secrets.")
31
-
32
- # ---------------- STREAMLIT UI SETUP ----------------
33
- st.set_page_config(page_title="PDF Assistant", page_icon="📘", layout="wide")
34
 
35
  # ---------------- CSS ----------------
36
  st.markdown("""
37
  <style>
38
- /* 1. GLOBAL RESET & SCROLL LOCK */
39
- html, body {
40
- overflow: hidden;
41
- height: 100%;
42
- margin: 0;
43
- }
44
 
45
- /* 2. HIDE DEFAULT STREAMLIT ELEMENTS */
46
- header[data-testid="stHeader"] {
47
- display: none;
48
- }
49
- footer {
50
- display: none;
51
- }
52
 
53
- /* 3. SIDEBAR STYLING (INDEPENDENT LEFT PANEL SCROLL) */
54
  [data-testid="stSidebar"] {
55
  position: fixed;
56
- top: 0;
57
  left: 0;
 
58
  height: 100vh;
59
  width: 20rem;
60
- overflow-y: auto !important;
61
- z-index: 99999;
 
62
  }
63
- [data-testid="stSidebar"]::-webkit-scrollbar {
64
- width: 6px;
 
 
65
  }
66
- [data-testid="stSidebar"]::-webkit-scrollbar-thumb {
67
- background: #2d3748;
68
- border-radius: 3px;
 
 
 
 
 
69
  }
70
 
71
- /* 4. FIXED HEADER STYLING */
72
  .fixed-header {
73
  position: fixed;
74
  top: 0;
75
- left: 0;
76
- width: 100%;
77
  height: 6rem;
78
- background-color: #0e1117;
79
- z-index: 99998;
80
  display: flex;
81
  flex-direction: column;
82
  justify-content: center;
83
  align-items: center;
84
- border-bottom: 1px solid rgba(255, 255, 255, 0.1);
85
  }
86
 
87
- /* 5. MAIN CONTENT SCROLLING (INDEPENDENT RIGHT PANEL SCROLL) */
88
- .main .block-container {
89
- margin-top: 6rem;
90
- height: calc(100vh - 6rem);
91
- overflow-y: auto;
92
- padding-top: 1rem;
93
- padding-bottom: 5rem;
94
- }
95
- .main .block-container::-webkit-scrollbar {
96
- width: 8px;
97
- }
98
- .main .block-container::-webkit-scrollbar-thumb {
99
- background: #2d3748;
100
- border-radius: 4px;
101
- }
102
 
103
- /* 6. SIDEBAR BUTTON STYLING */
104
  [data-testid="stSidebar"] .stButton button {
105
  width: 100%;
106
  border-radius: 8px;
107
  font-weight: 600;
108
- margin-bottom: 6px;
109
  }
110
 
111
- /* 7. HIDE UPLOADED FILE LIST & NAME */
112
- [data-testid='stFileUploaderFile'] {
113
- display: none;
114
- }
115
- section[data-testid="stFileUploader"] ul {
116
- display: none;
117
- }
118
- section[data-testid="stFileUploader"] small {
119
- display: none;
120
- }
121
-
122
- /* 8. CHAT BUBBLES */
123
  .chat-user {
124
- background: #2d3748;
125
- padding: 12px;
126
- border-radius: 10px 10px 2px 10px;
127
- margin: 6px 0 6px auto;
128
- max-width: 85%;
129
- text-align: right;
130
- color: #f0f2f6;
131
  }
132
  .chat-bot {
133
- background: #1e3a8a;
134
- padding: 12px;
135
- border-radius: 10px 10px 10px 2px;
136
- margin: 6px auto 6px 0;
137
- max-width: 85%;
138
- text-align: left;
139
- color: #ffffff;
140
- }
141
- /* Sources CSS removed/hidden as it is no longer used */
142
- .sources {
143
- display: none;
144
  }
145
 
146
- /* 9. TITLE TEXT */
147
- .title-text {
148
- font-size: 2.5rem;
149
- font-weight: 800;
150
- margin: 0;
151
- line-height: 1.2;
152
- }
153
- .creator-text {
154
- font-size: 1rem;
155
- font-weight: 500;
156
- color: #cccccc;
157
- }
158
- .creator-text a {
159
- color: #4da6ff;
160
- text-decoration: none;
161
- }
162
 
163
- /* 10. INPUT FORM STYLING */
164
- [data-testid="stForm"] {
165
- border: none;
166
- padding: 0;
167
- }
168
  </style>
169
  """, unsafe_allow_html=True)
170
 
@@ -178,164 +117,105 @@ st.markdown("""
178
  </div>
179
  """, unsafe_allow_html=True)
180
 
181
-
182
  # ---------------- SESSION STATE ----------------
183
- if "chat" not in st.session_state:
184
- st.session_state.chat = []
185
-
186
- if "vectorstore" not in st.session_state:
187
- st.session_state.vectorstore = None
188
-
189
- if "retriever" not in st.session_state:
190
- st.session_state.retriever = None
191
-
192
- if "uploaded_file_name" not in st.session_state:
193
- st.session_state.uploaded_file_name = None
194
-
195
- if "uploader_key" not in st.session_state:
196
- st.session_state.uploader_key = 0
197
 
198
  # ---------------- FUNCTIONS ----------------
199
- def clear_chat_history():
200
- st.session_state.chat = []
201
-
202
  def clear_memory():
203
  st.session_state.vectorstore = None
204
  st.session_state.retriever = None
 
205
  st.session_state.uploaded_file_name = None
206
  st.session_state.uploader_key += 1
207
  gc.collect()
208
  if torch.cuda.is_available():
209
  torch.cuda.empty_cache()
210
 
211
- def process_pdf(uploaded_file):
212
- try:
213
- with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
214
- tmp.write(uploaded_file.getvalue())
215
- path = tmp.name
216
-
217
- loader = PyPDFLoader(path)
218
- docs = loader.load()
219
-
220
- splitter = RecursiveCharacterTextSplitter(chunk_size=800, chunk_overlap=60)
221
- chunks = splitter.split_documents(docs)
222
-
223
- embeddings = HuggingFaceEmbeddings(
224
- model_name="sentence-transformers/all-MiniLM-L6-v2",
225
- model_kwargs={"device": "cpu"},
226
- encode_kwargs={"normalize_embeddings": True}
227
- )
228
-
229
- vectorstore = Chroma.from_documents(chunks, embeddings)
230
- retriever = vectorstore.as_retriever(search_kwargs={"k": 5})
231
-
232
- st.session_state.vectorstore = vectorstore
233
- st.session_state.retriever = retriever
234
-
235
- if os.path.exists(path):
236
- os.unlink(path)
237
-
238
- return len(chunks)
239
- except Exception as e:
240
- st.error(f"Error processing PDF: {str(e)}")
241
- return None
242
-
243
- def ask_question(question):
244
- if not client:
245
- return None, 0, "Groq client is not initialized."
246
- if not st.session_state.retriever:
247
- return None, 0, "Upload PDF first."
248
-
249
- try:
250
- docs = st.session_state.retriever.invoke(question)
251
- context = "\n\n".join(d.page_content for d in docs)
252
-
253
- prompt = f"""
254
- You are a strict RAG Q&A assistant.
255
- Summarize the context based on user question and return best answer. If the answer is not found, reply: "I cannot find this in the PDF."
256
- CONTEXT = {context}
257
- QUESTION = {question}
258
-
259
- Answer on your behalf, don't say based on the context...
260
  """
261
-
262
- response = client.chat.completions.create(
263
- model=GROQ_MODEL,
264
- messages=[
265
- {"role": "system", "content": "Use only the PDF content."},
266
- {"role": "user", "content": prompt}
267
- ],
268
- temperature=0.1
269
- )
270
- return response.choices[0].message.content.strip(), len(docs), None
271
- except Exception as e:
272
- return None, 0, f"Error: {str(e)}"
273
 
274
  # ---------------- SIDEBAR ----------------
275
  with st.sidebar:
276
- st.write("")
277
- if st.button("🗑️ Clear Chat History", use_container_width=True):
278
- clear_chat_history()
279
- if st.button("🔥 Clear PDF Memory", on_click=clear_memory, use_container_width=True):
280
- st.success("Memory Cleared!")
281
-
282
  st.markdown("---")
283
-
284
- upload_label = "✅ PDF Uploaded!" if st.session_state.uploaded_file_name else "Upload PDF"
285
  uploaded = st.file_uploader(
286
- upload_label, type=["pdf"], key=st.session_state.uploader_key, label_visibility="collapsed"
 
 
287
  )
288
 
289
- if uploaded:
290
- if uploaded.name != st.session_state.uploaded_file_name:
291
- st.session_state.uploaded_file_name = None
292
- st.session_state.chat = []
293
- with st.spinner(f"Processing '{uploaded.name}'..."):
294
- chunks = process_pdf(uploaded)
295
- if chunks:
296
- st.session_state.uploaded_file_name = uploaded.name
297
- st.success("✅ PDF Processed!")
298
- else:
299
- st.error("❌ Failed.")
300
- else:
301
- st.success(f"✅ **Active:** `{uploaded.name}`")
302
- else:
303
- st.warning("⬆️ Upload a PDF to start chatting!")
304
-
305
- # ---------------- INPUT AREA ----------------
306
- disabled_input = st.session_state.uploaded_file_name is None or client is None
307
-
308
- # Input Form
309
- with st.form(key='chat_form', clear_on_submit=True):
310
- col_input, col_btn = st.columns([0.85, 0.15], gap="small")
311
- with col_input:
312
- user_question = st.text_input(
313
- "Ask a question",
314
- placeholder="Ask a question about the loaded PDF...",
315
- label_visibility="collapsed",
316
- disabled=disabled_input
317
- )
318
- with col_btn:
319
- submit_btn = st.form_submit_button("➤", disabled=disabled_input, use_container_width=True)
320
-
321
- if submit_btn and user_question:
322
- st.session_state.chat.append(("user", user_question))
323
  with st.spinner("Thinking..."):
324
- answer, sources, error = ask_question(user_question)
325
- if answer:
326
- # CHANGED: Removed the 'Context Chunks Used' HTML from the message
327
- bot_msg = answer
328
- st.session_state.chat.append(("bot", bot_msg))
329
- else:
330
- st.session_state.chat.append(("bot", f"🔴 **Error:** {error}"))
331
  st.rerun()
332
 
333
- # ---------------- CHAT HISTORY (REVERSED) ----------------
334
- if st.session_state.chat:
335
- st.markdown("---")
336
- for role, msg in reversed(st.session_state.chat):
337
- if role == "user":
338
- st.markdown(f"<div class='chat-user'>{msg}</div>", unsafe_allow_html=True)
339
- else:
340
- st.markdown(f"<div class='chat-bot'>{msg}</div>", unsafe_allow_html=True)
341
- #check
 
3
  import gc
4
  import logging
5
  import streamlit as st
6
+ from groq import Groq
7
  from langchain_community.document_loaders import PyPDFLoader
8
  from langchain_text_splitters import RecursiveCharacterTextSplitter
9
  from langchain_community.embeddings import HuggingFaceEmbeddings
10
  from langchain_community.vectorstores import Chroma
11
  import torch
12
 
13
+ # ---------------- CONFIG ----------------
14
+ st.set_page_config(page_title="PDF Assistant", page_icon="📘", layout="wide")
15
  logging.basicConfig(level=logging.INFO)
16
 
 
17
  GROQ_API_KEY = st.secrets.get("GROQ_API_KEY", os.environ.get("GROQ_API_KEY"))
18
  GROQ_MODEL = "llama-3.1-8b-instant"
19
 
20
+ client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
  # ---------------- CSS ----------------
23
  st.markdown("""
24
  <style>
 
 
 
 
 
 
25
 
26
+ /* DO NOT TOUCH html/body (CRITICAL) */
27
+
28
+ /* Hide default header/footer */
29
+ header[data-testid="stHeader"], footer {display:none;}
 
 
 
30
 
31
+ /* ===== FIXED SIDEBAR ===== */
32
  [data-testid="stSidebar"] {
33
  position: fixed;
 
34
  left: 0;
35
+ top: 0;
36
  height: 100vh;
37
  width: 20rem;
38
+ background: #0e1117;
39
+ z-index: 9999;
40
+ overflow-y: auto;
41
  }
42
+
43
+ /* Sidebar inner padding */
44
+ [data-testid="stSidebar"] > div {
45
+ padding: 1rem;
46
  }
47
+
48
+ /* ===== FIX MAIN CONTENT OFFSET ===== */
49
+ .main .block-container {
50
+ margin-left: 20rem; /* SAME AS SIDEBAR WIDTH */
51
+ margin-top: 6rem;
52
+ height: calc(100vh - 6rem);
53
+ overflow-y: auto;
54
+ padding-bottom: 4rem;
55
  }
56
 
57
+ /* ===== FIXED HEADER ===== */
58
  .fixed-header {
59
  position: fixed;
60
  top: 0;
61
+ left: 20rem; /* START AFTER SIDEBAR */
62
+ width: calc(100% - 20rem);
63
  height: 6rem;
64
+ background: #0e1117;
65
+ z-index: 9998;
66
  display: flex;
67
  flex-direction: column;
68
  justify-content: center;
69
  align-items: center;
70
+ border-bottom: 1px solid rgba(255,255,255,0.1);
71
  }
72
 
73
+ /* Scrollbars */
74
+ .main .block-container::-webkit-scrollbar {width: 8px;}
75
+ .main .block-container::-webkit-scrollbar-thumb {background:#2d3748;border-radius:4px;}
76
+ [data-testid="stSidebar"]::-webkit-scrollbar {width: 6px;}
77
+ [data-testid="stSidebar"]::-webkit-scrollbar-thumb {background:#2d3748;border-radius:3px;}
 
 
 
 
 
 
 
 
 
 
78
 
79
+ /* Buttons */
80
  [data-testid="stSidebar"] .stButton button {
81
  width: 100%;
82
  border-radius: 8px;
83
  font-weight: 600;
 
84
  }
85
 
86
+ /* Chat bubbles */
 
 
 
 
 
 
 
 
 
 
 
87
  .chat-user {
88
+ background:#2d3748;
89
+ padding:12px;
90
+ border-radius:10px 10px 2px 10px;
91
+ margin:6px 0 6px auto;
92
+ max-width:85%;
93
+ text-align:right;
 
94
  }
95
  .chat-bot {
96
+ background:#1e3a8a;
97
+ padding:12px;
98
+ border-radius:10px 10px 10px 2px;
99
+ margin:6px auto 6px 0;
100
+ max-width:85%;
 
 
 
 
 
 
101
  }
102
 
103
+ /* Title */
104
+ .title-text {font-size:2.5rem;font-weight:800;}
105
+ .creator-text {font-size:1rem;color:#ccc;}
 
 
 
 
 
 
 
 
 
 
 
 
 
106
 
 
 
 
 
 
107
  </style>
108
  """, unsafe_allow_html=True)
109
 
 
117
  </div>
118
  """, unsafe_allow_html=True)
119
 
 
120
  # ---------------- SESSION STATE ----------------
121
+ for k, v in {
122
+ "chat": [],
123
+ "vectorstore": None,
124
+ "retriever": None,
125
+ "uploaded_file_name": None,
126
+ "uploader_key": 0
127
+ }.items():
128
+ st.session_state.setdefault(k, v)
 
 
 
 
 
 
129
 
130
  # ---------------- FUNCTIONS ----------------
 
 
 
131
  def clear_memory():
132
  st.session_state.vectorstore = None
133
  st.session_state.retriever = None
134
+ st.session_state.chat = []
135
  st.session_state.uploaded_file_name = None
136
  st.session_state.uploader_key += 1
137
  gc.collect()
138
  if torch.cuda.is_available():
139
  torch.cuda.empty_cache()
140
 
141
+ def process_pdf(file):
142
+ with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
143
+ tmp.write(file.getvalue())
144
+ path = tmp.name
145
+
146
+ docs = PyPDFLoader(path).load()
147
+ chunks = RecursiveCharacterTextSplitter(
148
+ chunk_size=800, chunk_overlap=60
149
+ ).split_documents(docs)
150
+
151
+ embeddings = HuggingFaceEmbeddings(
152
+ model_name="sentence-transformers/all-MiniLM-L6-v2",
153
+ model_kwargs={"device": "cpu"},
154
+ encode_kwargs={"normalize_embeddings": True}
155
+ )
156
+
157
+ vs = Chroma.from_documents(chunks, embeddings)
158
+ st.session_state.vectorstore = vs
159
+ st.session_state.retriever = vs.as_retriever(search_kwargs={"k": 5})
160
+ os.unlink(path)
161
+
162
+ def ask_question(q):
163
+ docs = st.session_state.retriever.invoke(q)
164
+ context = "\n\n".join(d.page_content for d in docs)
165
+
166
+ prompt = f"""
167
+ Use ONLY the context.
168
+ If not found say: I cannot find this in the PDF.
169
+
170
+ CONTEXT:
171
+ {context}
172
+
173
+ QUESTION:
174
+ {q}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  """
176
+
177
+ res = client.chat.completions.create(
178
+ model=GROQ_MODEL,
179
+ messages=[{"role":"user","content":prompt}],
180
+ temperature=0.1
181
+ )
182
+ return res.choices[0].message.content.strip()
 
 
 
 
 
183
 
184
  # ---------------- SIDEBAR ----------------
185
  with st.sidebar:
186
+ st.button("🗑️ Clear Chat", on_click=lambda: st.session_state.chat.clear())
187
+ st.button("🔥 Clear PDF Memory", on_click=clear_memory)
 
 
 
 
188
  st.markdown("---")
189
+
 
190
  uploaded = st.file_uploader(
191
+ "Upload PDF",
192
+ type=["pdf"],
193
+ key=st.session_state.uploader_key
194
  )
195
 
196
+ if uploaded and uploaded.name != st.session_state.uploaded_file_name:
197
+ with st.spinner("Processing PDF..."):
198
+ process_pdf(uploaded)
199
+ st.session_state.uploaded_file_name = uploaded.name
200
+ st.success("PDF Ready")
201
+
202
+ # ---------------- CHAT INPUT ----------------
203
+ disabled = not st.session_state.retriever or not client
204
+
205
+ with st.form("chat_form", clear_on_submit=True):
206
+ q = st.text_input("Ask", label_visibility="collapsed", disabled=disabled)
207
+ send = st.form_submit_button("➤", disabled=disabled)
208
+
209
+ if send and q:
210
+ st.session_state.chat.append(("user", q))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  with st.spinner("Thinking..."):
212
+ ans = ask_question(q)
213
+ st.session_state.chat.append(("bot", ans))
 
 
 
 
 
214
  st.rerun()
215
 
216
+ # ---------------- CHAT DISPLAY ----------------
217
+ for role, msg in reversed(st.session_state.chat):
218
+ st.markdown(
219
+ f"<div class='chat-{'user' if role=='user' else 'bot'}'>{msg}</div>",
220
+ unsafe_allow_html=True
221
+ )