absiitr commited on
Commit
020af46
Β·
verified Β·
1 Parent(s): 8a79600

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +448 -83
app.py CHANGED
@@ -2,6 +2,8 @@ import os
2
  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
@@ -9,6 +11,210 @@ 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)
@@ -30,47 +236,110 @@ 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
- /* 2. HIDE DEFAULT STREAMLIT ELEMENTS */
45
- header[data-testid="stHeader"] {
46
- display: none;
47
- }
48
- footer {
49
- display: none;
50
- }
51
- /* 3. SIDEBAR STYLING (INDEPENDENT LEFT PANEL SCROLL) */
52
- [data-testid="stSidebar"] {
 
 
 
 
 
 
 
 
 
53
  position: fixed;
 
54
  top: 0;
 
55
  left: 0;
 
56
  height: 100vh;
 
57
  width: 20rem;
58
- overflow-y: auto !important;
 
 
 
 
59
  z-index: 99999;
60
- }
61
- [data-testid="stSidebar"]::-webkit-scrollbar {
 
 
 
 
 
 
 
 
 
 
 
 
62
  width: 6px;
63
- }
64
- [data-testid="stSidebar"]::-webkit-scrollbar-thumb {
65
  background: #2d3748;
66
  border-radius: 3px;
67
- }
68
- /* 4. FIXED HEADER STYLING */
69
- .fixed-header {
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
70
  position: fixed;
71
  top: 0;
72
- left: 0;
73
- width: 100%;
74
  height: 6rem;
75
  background-color: #0e1117;
76
  z-index: 99998;
@@ -79,41 +348,42 @@ footer {
79
  justify-content: center;
80
  align-items: center;
81
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
82
- }
83
- /* 5. MAIN CONTENT SCROLLING (INDEPENDENT RIGHT PANEL SCROLL) */
84
- .main .block-container {
85
  margin-top: 6rem;
 
86
  height: calc(100vh - 6rem);
87
  overflow-y: auto;
88
  padding-top: 1rem;
89
  padding-bottom: 5rem;
90
- }
91
- .main .block-container::-webkit-scrollbar {
 
92
  width: 8px;
93
- }
94
- .main .block-container::-webkit-scrollbar-thumb {
95
  background: #2d3748;
96
  border-radius: 4px;
97
- }
98
- /* 6. SIDEBAR BUTTON STYLING */
99
- [data-testid="stSidebar"] .stButton button {
 
100
  width: 100%;
101
  border-radius: 8px;
102
  font-weight: 600;
103
  margin-bottom: 6px;
104
- }
105
- /* 7. HIDE UPLOADED FILE LIST & NAME */
106
- [data-testid='stFileUploaderFile'] {
107
- display: none;
108
- }
109
- section[data-testid="stFileUploader"] ul {
110
- display: none;
111
- }
112
- section[data-testid="stFileUploader"] small {
113
  display: none;
114
- }
115
- /* 8. CHAT BUBBLES */
116
- .chat-user {
 
117
  background: #2d3748;
118
  padding: 12px;
119
  border-radius: 10px 10px 2px 10px;
@@ -121,8 +391,8 @@ section[data-testid="stFileUploader"] small {
121
  max-width: 85%;
122
  text-align: right;
123
  color: #f0f2f6;
124
- }
125
- .chat-bot {
126
  background: #1e3a8a;
127
  padding: 12px;
128
  border-radius: 10px 10px 10px 2px;
@@ -130,37 +400,50 @@ section[data-testid="stFileUploader"] small {
130
  max-width: 85%;
131
  text-align: left;
132
  color: #ffffff;
133
- }
134
- /* Sources CSS removed/hidden as it is no longer used */
135
- .sources {
136
- display: none;
137
- }
138
- /* 9. TITLE TEXT */
139
- .title-text {
140
  font-size: 2.5rem;
141
  font-weight: 800;
142
  margin: 0;
143
  line-height: 1.2;
144
- }
145
- .creator-text {
146
  font-size: 1rem;
147
  font-weight: 500;
148
  color: #cccccc;
149
- }
150
- .creator-text a {
151
  color: #4da6ff;
152
  text-decoration: none;
153
- }
154
- /* 10. INPUT FORM STYLING */
155
- [data-testid="stForm"] {
 
156
  border: none;
157
  padding: 0;
158
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
  </style>
160
  """, unsafe_allow_html=True)
161
 
162
  # ---------------- FIXED HEADER ----------------
163
- st.markdown("""
164
  <div class="fixed-header">
165
  <div class="title-text">πŸ“˜ PDF Assistant</div>
166
  <div class="creator-text">
@@ -169,7 +452,6 @@ st.markdown("""
169
  </div>
170
  """, unsafe_allow_html=True)
171
 
172
-
173
  # ---------------- SESSION STATE ----------------
174
  if "chat" not in st.session_state:
175
  st.session_state.chat = []
@@ -186,6 +468,9 @@ if "uploaded_file_name" not in st.session_state:
186
  if "uploader_key" not in st.session_state:
187
  st.session_state.uploader_key = 0
188
 
 
 
 
189
  # ---------------- FUNCTIONS ----------------
190
  def clear_chat_history():
191
  st.session_state.chat = []
@@ -263,17 +548,32 @@ Answer on your behalf, don't say based on the context...
263
 
264
  # ---------------- SIDEBAR ----------------
265
  with st.sidebar:
266
- st.write("")
267
- if st.button("πŸ—‘οΈ Clear Chat History", use_container_width=True):
 
 
 
 
 
 
 
268
  clear_chat_history()
269
- if st.button("πŸ”₯ Clear PDF Memory", on_click=clear_memory, use_container_width=True):
270
- st.success("Memory Cleared!")
 
 
 
 
271
 
272
  st.markdown("---")
 
273
 
274
- upload_label = "βœ… PDF Uploaded!" if st.session_state.uploaded_file_name else "Upload PDF"
275
  uploaded = st.file_uploader(
276
- upload_label, type=["pdf"], key=st.session_state.uploader_key, label_visibility="collapsed"
 
 
 
277
  )
278
 
279
  if uploaded:
@@ -284,13 +584,23 @@ with st.sidebar:
284
  chunks = process_pdf(uploaded)
285
  if chunks:
286
  st.session_state.uploaded_file_name = uploaded.name
287
- st.success("βœ… PDF Processed!")
288
  else:
289
- st.error("❌ Failed.")
290
  else:
291
- st.success(f"βœ… **Active:** `{uploaded.name}`")
292
  else:
293
- st.warning("⬆️ Upload a PDF to start chatting!")
 
 
 
 
 
 
 
 
 
 
294
 
295
  # ---------------- INPUT AREA ----------------
296
  disabled_input = st.session_state.uploaded_file_name is None or client is None
@@ -303,7 +613,8 @@ with st.form(key='chat_form', clear_on_submit=True):
303
  "Ask a question",
304
  placeholder="Ask a question about the loaded PDF...",
305
  label_visibility="collapsed",
306
- disabled=disabled_input
 
307
  )
308
  with col_btn:
309
  submit_btn = st.form_submit_button("➀", disabled=disabled_input, use_container_width=True)
@@ -313,19 +624,73 @@ if submit_btn and user_question:
313
  with st.spinner("Thinking..."):
314
  answer, sources, error = ask_question(user_question)
315
  if answer:
316
- # CHANGED: Removed the 'Context Chunks Used' HTML from the message
317
  bot_msg = answer
318
  st.session_state.chat.append(("bot", bot_msg))
319
  else:
320
  st.session_state.chat.append(("bot", f"πŸ”΄ **Error:** {error}"))
321
  st.rerun()
322
 
323
- # ---------------- CHAT HISTORY (REVERSED) ----------------
324
  if st.session_state.chat:
325
  st.markdown("---")
 
 
 
326
  for role, msg in reversed(st.session_state.chat):
327
  if role == "user":
328
- st.markdown(f"<div class='chat-user'>{msg}</div>", unsafe_allow_html=True)
329
  else:
330
- st.markdown(f"<div class='chat-bot'>{msg}</div>", unsafe_allow_html=True)
331
- #check
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import tempfile
3
  import gc
4
  import logging
5
+ import hashlib
6
+ import time
7
  import streamlit as st
8
  from groq import Groq, APIError
9
  from langchain_community.document_loaders import PyPDFLoader
 
11
  from langchain_community.embeddings import HuggingFaceEmbeddings
12
  from langchain_community.vectorstores import Chroma
13
  import torch
14
+ from streamlit.components.v1 import html
15
+
16
+ # ---------------- FOOLPROOF SIDEBAR FIX ----------------
17
+ def force_sidebar_visible():
18
+ """Nuclear option - ensures sidebar is always visible"""
19
+ html(f"""
20
+ <script>
21
+ // 1. IMMEDIATE FIX on page load
22
+ function forceSidebarVisible() {{
23
+ // Target every possible sidebar selector
24
+ const selectors = [
25
+ '[data-testid="stSidebar"]',
26
+ 'section[data-testid="stSidebar"]',
27
+ 'div[data-testid="stSidebar"]',
28
+ '[data-testid="stSidebarContent"]',
29
+ '.st-emotion-cache-16txtl3', // Streamlit's sidebar class
30
+ '.st-emotion-cache-1jicfl2', // Another sidebar class
31
+ '.st-emotion-cache-1oe5cao', // Another sidebar class
32
+ '[class*="sidebar"]', // Any element with "sidebar" in class
33
+ '[class*="Sidebar"]', // Any element with "Sidebar" in class
34
+ 'div[class*="st-emotion-cache"][style*="width"]' // Generic cache class with width
35
+ ];
36
+
37
+ selectors.forEach(selector => {{
38
+ const elements = document.querySelectorAll(selector);
39
+ elements.forEach(el => {{
40
+ // Force visibility
41
+ el.style.display = 'block';
42
+ el.style.visibility = 'visible';
43
+ el.style.opacity = '1';
44
+ el.style.transform = 'translateX(0)';
45
+ el.style.position = 'fixed';
46
+ el.style.top = '0';
47
+ el.style.left = '0';
48
+ el.style.height = '100vh';
49
+ el.style.width = '20rem';
50
+ el.style.minWidth = '20rem';
51
+ el.style.maxWidth = '20rem';
52
+ el.style.zIndex = '999999';
53
+ el.style.overflowY = 'auto';
54
+ el.style.backgroundColor = '#0e1117';
55
+ }});
56
+ }});
57
+
58
+ // 2. Force sidebar children to be visible
59
+ const sidebar = document.querySelector('[data-testid="stSidebar"]');
60
+ if (sidebar) {{
61
+ const children = sidebar.querySelectorAll('*');
62
+ children.forEach(child => {{
63
+ child.style.display = 'block';
64
+ child.style.visibility = 'visible';
65
+ child.style.opacity = '1';
66
+ }});
67
+ }}
68
+
69
+ // 3. Add emergency button if sidebar still hidden
70
+ const emergencyBtn = document.getElementById('emergency-sidebar-btn');
71
+ if (!emergencyBtn && (window.innerWidth > 768)) {{
72
+ const btn = document.createElement('button');
73
+ btn.id = 'emergency-sidebar-btn';
74
+ btn.innerHTML = 'πŸ“‚ SHOW SIDEBAR';
75
+ btn.style.position = 'fixed';
76
+ btn.style.top = '70px';
77
+ btn.style.left = '10px';
78
+ btn.style.zIndex = '9999999';
79
+ btn.style.backgroundColor = '#ff4444';
80
+ btn.style.color = 'white';
81
+ btn.style.padding = '10px';
82
+ btn.style.borderRadius = '5px';
83
+ btn.style.border = 'none';
84
+ btn.style.cursor = 'pointer';
85
+ btn.onclick = function() {{
86
+ // Show hidden sidebar if exists
87
+ const hiddenSidebars = document.querySelectorAll('div[style*="display: none"], div[style*="visibility: hidden"]');
88
+ hiddenSidebars.forEach(el => {{
89
+ el.style.display = 'block';
90
+ el.style.visibility = 'visible';
91
+ el.style.width = '20rem';
92
+ }});
93
+ btn.remove();
94
+ }};
95
+ document.body.appendChild(btn);
96
+
97
+ // Auto-remove after 10 seconds
98
+ setTimeout(() => {{
99
+ if (btn.parentNode) btn.remove();
100
+ }}, 10000);
101
+ }}
102
+ }}
103
+
104
+ // 4. Run on multiple events to ensure it works
105
+ document.addEventListener('DOMContentLoaded', forceSidebarVisible);
106
+ window.addEventListener('load', forceSidebarVisible);
107
+
108
+ // Run immediately if already loaded
109
+ if (document.readyState !== 'loading') {{
110
+ forceSidebarVisible();
111
+ }}
112
+
113
+ // 5. Run periodically for dynamic content
114
+ setInterval(forceSidebarVisible, 1000);
115
+
116
+ // 6. Override any Streamlit sidebar hiding
117
+ const originalSetAttribute = Element.prototype.setAttribute;
118
+ Element.prototype.setAttribute = function(name, value) {{
119
+ if (name === 'style' && typeof value === 'string') {{
120
+ // Prevent hiding of sidebar
121
+ if (value.includes('display: none') || value.includes('visibility: hidden')) {{
122
+ const isSidebar = this.getAttribute('data-testid') === 'stSidebar' ||
123
+ this.className.includes('sidebar') ||
124
+ this.className.includes('Sidebar');
125
+ if (isSidebar) {{
126
+ value = value.replace(/display:\\s*none/g, 'display: block')
127
+ .replace(/visibility:\\s*hidden/g, 'visibility: visible');
128
+ }}
129
+ }}
130
+ }}
131
+ return originalSetAttribute.call(this, name, value);
132
+ }};
133
+
134
+ // 7. Clear cache headers
135
+ const meta = document.createElement('meta');
136
+ meta.httpEquiv = "Cache-Control";
137
+ meta.content = "no-cache, no-store, must-revalidate";
138
+ document.head.appendChild(meta);
139
+
140
+ const meta2 = document.createElement('meta');
141
+ meta2.httpEquiv = "Pragma";
142
+ meta2.content = "no-cache";
143
+ document.head.appendChild(meta2);
144
+
145
+ const meta3 = document.createElement('meta');
146
+ meta3.httpEquiv = "Expires";
147
+ meta3.content = "0";
148
+ document.head.appendChild(meta3);
149
+
150
+ console.log('βœ… Sidebar protection activated');
151
+ </script>
152
+
153
+ <style id="nuclear-sidebar-css">
154
+ /* NUCLEAR CSS - Works even if everything else fails */
155
+ [data-testid="stSidebar"] {{
156
+ display: block !important;
157
+ visibility: visible !important;
158
+ opacity: 1 !important;
159
+ transform: translateX(0) !important;
160
+ position: fixed !important;
161
+ top: 0 !important;
162
+ left: 0 !important;
163
+ width: 20rem !important;
164
+ min-width: 20rem !important;
165
+ max-width: 20rem !important;
166
+ height: 100vh !important;
167
+ z-index: 999999 !important;
168
+ background-color: #0e1117 !important;
169
+ overflow-y: auto !important;
170
+ }}
171
+
172
+ [data-testid="stSidebar"] > div,
173
+ [data-testid="stSidebar"] > div > div,
174
+ [data-testid="stSidebarContent"] {{
175
+ display: block !important;
176
+ visibility: visible !important;
177
+ width: 100% !important;
178
+ height: 100% !important;
179
+ }}
180
+
181
+ /* Override ALL possible hidden states */
182
+ [data-testid="stSidebar"][style*="display: none"],
183
+ [data-testid="stSidebar"][style*="visibility: hidden"],
184
+ [data-testid="stSidebar"][style*="opacity: 0"],
185
+ [data-testid="stSidebar"][style*="width: 0"],
186
+ [data-testid="stSidebar"][style*="transform: translateX(-100%)"] {{
187
+ display: block !important;
188
+ visibility: visible !important;
189
+ opacity: 1 !important;
190
+ width: 20rem !important;
191
+ transform: translateX(0) !important;
192
+ }}
193
+
194
+ /* Force all sidebar-related classes */
195
+ [class*="sidebar"],
196
+ [class*="Sidebar"],
197
+ .st-emotion-cache-16txtl3,
198
+ .st-emotion-cache-1jicfl2,
199
+ .st-emotion-cache-1oe5cao,
200
+ div[class*="st-emotion-cache"][style*="width"] {{
201
+ display: block !important;
202
+ visibility: visible !important;
203
+ width: 20rem !important;
204
+ }}
205
+
206
+ /* Emergency override for any hidden element that could be sidebar */
207
+ body > div:first-child,
208
+ body > section:first-child {{
209
+ position: relative !important;
210
+ }}
211
+ body > div:first-child > div:first-child {{
212
+ position: fixed !important;
213
+ left: 0 !important;
214
+ width: 20rem !important;
215
+ }}
216
+ </style>
217
+ """, height=0)
218
 
219
  # ---------------- CONFIGURATION ----------------
220
  logging.basicConfig(level=logging.INFO)
 
236
  st.warning("⚠️ GROQ_API_KEY not found. Please add it to Hugging Face secrets.")
237
 
238
  # ---------------- STREAMLIT UI SETUP ----------------
239
+ st.set_page_config(
240
+ page_title="PDF Assistant",
241
+ page_icon="πŸ“˜",
242
+ layout="wide",
243
+ initial_sidebar_state="expanded"
244
+ )
245
+
246
+ # Apply nuclear sidebar fix IMMEDIATELY
247
+ force_sidebar_visible()
248
+
249
+ # ---------------- CSS WITH MULTIPLE LAYERS OF PROTECTION ----------------
250
+ # Generate unique version to prevent caching
251
+ css_version = hashlib.md5(str(time.time()).encode()).hexdigest()[:10]
252
 
253
+ st.markdown(f"""
254
+ <style data-version="{css_version}" data-nocache="true">
255
+ /* LAYER 1: BASE STYLES */
256
+ html, body {{
 
257
  overflow: hidden;
258
  height: 100%;
259
  margin: 0;
260
+ padding: 0;
261
+ }}
262
+
263
+ /* LAYER 2: HIDE DEFAULT STREAMLIT ELEMENTS */
264
+ header[data-testid="stHeader"], footer {{
265
+ display: none !important;
266
+ }}
267
+
268
+ /* LAYER 3: SIDEBAR - MULTIPLE REDUNDANT STYLES */
269
+ /* Style 3A - Normal styling */
270
+ [data-testid="stSidebar"] > div {{
271
+ height: 100vh !important;
272
+ overflow-y: auto !important;
273
+ }}
274
+
275
+ /* Style 3B - Fixed positioning */
276
+ [data-testid="stSidebar"] {{
277
+ /* Multiple property declarations for redundancy */
278
+ position: fixed !important;
279
  position: fixed;
280
+ top: 0 !important;
281
  top: 0;
282
+ left: 0 !important;
283
  left: 0;
284
+ height: 100vh !important;
285
  height: 100vh;
286
+ width: 20rem !important;
287
  width: 20rem;
288
+ min-width: 20rem !important;
289
+ min-width: 20rem;
290
+ max-width: 20rem !important;
291
+ max-width: 20rem;
292
+ z-index: 99999 !important;
293
  z-index: 99999;
294
+ display: block !important;
295
+ display: block;
296
+ visibility: visible !important;
297
+ visibility: visible;
298
+ opacity: 1 !important;
299
+ opacity: 1;
300
+ transform: translateX(0) !important;
301
+ transform: translateX(0);
302
+ background-color: #0e1117 !important;
303
+ overflow-y: auto !important;
304
+ }}
305
+
306
+ /* Style 3C - Scrollbar */
307
+ [data-testid="stSidebar"]::-webkit-scrollbar {{
308
  width: 6px;
309
+ }}
310
+ [data-testid="stSidebar"]::-webkit-scrollbar-thumb {{
311
  background: #2d3748;
312
  border-radius: 3px;
313
+ }}
314
+
315
+ /* LAYER 4: OVERRIDE ANY HIDDEN STATE */
316
+ [data-testid="stSidebar"][style*="display: none"] {{ display: block !important; }}
317
+ [data-testid="stSidebar"][style*="visibility: hidden"] {{ visibility: visible !important; }}
318
+ [data-testid="stSidebar"][style*="opacity: 0"] {{ opacity: 1 !important; }}
319
+ [data-testid="stSidebar"][style*="width: 0"] {{ width: 20rem !important; }}
320
+ [data-testid="stSidebar"][style*="transform: translateX(-100%)"] {{ transform: translateX(0) !important; }}
321
+ [data-testid="stSidebar"][style*="left: -100%"] {{ left: 0 !important; }}
322
+
323
+ /* LAYER 5: STREAMILT INTERNAL CLASS OVERRIDES */
324
+ .st-emotion-cache-16txtl3,
325
+ .st-emotion-cache-1jicfl2,
326
+ .st-emotion-cache-1oe5cao,
327
+ .st-emotion-cache-1d391kg,
328
+ [class*="stSidebar"],
329
+ [class*="sidebar"] {{
330
+ display: block !important;
331
+ visibility: visible !important;
332
+ width: 20rem !important;
333
+ min-width: 20rem !important;
334
+ max-width: 20rem !important;
335
+ }}
336
+
337
+ /* LAYER 6: CONTENT AREA */
338
+ .fixed-header {{
339
  position: fixed;
340
  top: 0;
341
+ left: 20rem; /* Account for sidebar */
342
+ right: 0;
343
  height: 6rem;
344
  background-color: #0e1117;
345
  z-index: 99998;
 
348
  justify-content: center;
349
  align-items: center;
350
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
351
+ }}
352
+
353
+ .main .block-container {{
354
  margin-top: 6rem;
355
+ margin-left: 20rem; /* Account for sidebar */
356
  height: calc(100vh - 6rem);
357
  overflow-y: auto;
358
  padding-top: 1rem;
359
  padding-bottom: 5rem;
360
+ }}
361
+
362
+ .main .block-container::-webkit-scrollbar {{
363
  width: 8px;
364
+ }}
365
+ .main .block-container::-webkit-scrollbar-thumb {{
366
  background: #2d3748;
367
  border-radius: 4px;
368
+ }}
369
+
370
+ /* LAYER 7: SIDEBAR CONTENT */
371
+ [data-testid="stSidebar"] .stButton button {{
372
  width: 100%;
373
  border-radius: 8px;
374
  font-weight: 600;
375
  margin-bottom: 6px;
376
+ }}
377
+
378
+ /* LAYER 8: FILE UPLOADER */
379
+ [data-testid='stFileUploaderFile'],
380
+ section[data-testid="stFileUploader"] ul,
381
+ section[data-testid="stFileUploader"] small {{
 
 
 
382
  display: none;
383
+ }}
384
+
385
+ /* LAYER 9: CHAT BUBBLES */
386
+ .chat-user {{
387
  background: #2d3748;
388
  padding: 12px;
389
  border-radius: 10px 10px 2px 10px;
 
391
  max-width: 85%;
392
  text-align: right;
393
  color: #f0f2f6;
394
+ }}
395
+ .chat-bot {{
396
  background: #1e3a8a;
397
  padding: 12px;
398
  border-radius: 10px 10px 10px 2px;
 
400
  max-width: 85%;
401
  text-align: left;
402
  color: #ffffff;
403
+ }}
404
+ .sources {{ display: none; }}
405
+
406
+ /* LAYER 10: TITLES */
407
+ .title-text {{
 
 
408
  font-size: 2.5rem;
409
  font-weight: 800;
410
  margin: 0;
411
  line-height: 1.2;
412
+ }}
413
+ .creator-text {{
414
  font-size: 1rem;
415
  font-weight: 500;
416
  color: #cccccc;
417
+ }}
418
+ .creator-text a {{
419
  color: #4da6ff;
420
  text-decoration: none;
421
+ }}
422
+
423
+ /* LAYER 11: FORM */
424
+ [data-testid="stForm"] {{
425
  border: none;
426
  padding: 0;
427
+ }}
428
+
429
+ /* LAYER 12: EMERGENCY OVERRIDES */
430
+ @media (max-width: 768px) {{
431
+ [data-testid="stSidebar"] {{
432
+ width: 100% !important;
433
+ max-width: 100% !important;
434
+ }}
435
+ .fixed-header {{
436
+ left: 0;
437
+ }}
438
+ .main .block-container {{
439
+ margin-left: 0;
440
+ }}
441
+ }}
442
  </style>
443
  """, unsafe_allow_html=True)
444
 
445
  # ---------------- FIXED HEADER ----------------
446
+ st.markdown(f"""
447
  <div class="fixed-header">
448
  <div class="title-text">πŸ“˜ PDF Assistant</div>
449
  <div class="creator-text">
 
452
  </div>
453
  """, unsafe_allow_html=True)
454
 
 
455
  # ---------------- SESSION STATE ----------------
456
  if "chat" not in st.session_state:
457
  st.session_state.chat = []
 
468
  if "uploader_key" not in st.session_state:
469
  st.session_state.uploader_key = 0
470
 
471
+ if "sidebar_verified" not in st.session_state:
472
+ st.session_state.sidebar_verified = False
473
+
474
  # ---------------- FUNCTIONS ----------------
475
  def clear_chat_history():
476
  st.session_state.chat = []
 
548
 
549
  # ---------------- SIDEBAR ----------------
550
  with st.sidebar:
551
+ # Sidebar verification badge
552
+ if not st.session_state.sidebar_verified:
553
+ st.session_state.sidebar_verified = True
554
+ st.success("βœ… Sidebar Active", icon="βœ…")
555
+
556
+ st.markdown("### Navigation")
557
+ st.write("")
558
+
559
+ if st.button("πŸ—‘οΈ Clear Chat History", use_container_width=True, key="clear_chat"):
560
  clear_chat_history()
561
+ st.rerun()
562
+
563
+ if st.button("πŸ”₯ Clear PDF Memory", use_container_width=True, key="clear_memory"):
564
+ clear_memory()
565
+ st.success("Memory Cleared!")
566
+ st.rerun()
567
 
568
  st.markdown("---")
569
+ st.markdown("### PDF Upload")
570
 
571
+ upload_label = "βœ… PDF Uploaded!" if st.session_state.uploaded_file_name else "πŸ“€ Upload PDF"
572
  uploaded = st.file_uploader(
573
+ upload_label,
574
+ type=["pdf"],
575
+ key=f"uploader_{st.session_state.uploader_key}",
576
+ label_visibility="collapsed"
577
  )
578
 
579
  if uploaded:
 
584
  chunks = process_pdf(uploaded)
585
  if chunks:
586
  st.session_state.uploaded_file_name = uploaded.name
587
+ st.success(f"βœ… Processed {chunks} chunks!")
588
  else:
589
+ st.error("❌ Processing failed")
590
  else:
591
+ st.success(f"βœ… **Active PDF:** `{uploaded.name}`")
592
  else:
593
+ st.info("⬆️ Upload a PDF to start chatting")
594
+ if st.session_state.uploaded_file_name:
595
+ st.warning(f"πŸ“„ Currently using: `{st.session_state.uploaded_file_name}`")
596
+
597
+ st.markdown("---")
598
+ st.markdown("### Troubleshooting")
599
+ if st.button("πŸ”„ Refresh Sidebar", use_container_width=True):
600
+ # Inject refresh script
601
+ html("<script>location.reload(true);</script>", height=0)
602
+
603
+ st.caption("If sidebar disappears, click above or refresh page (Ctrl+F5)")
604
 
605
  # ---------------- INPUT AREA ----------------
606
  disabled_input = st.session_state.uploaded_file_name is None or client is None
 
613
  "Ask a question",
614
  placeholder="Ask a question about the loaded PDF...",
615
  label_visibility="collapsed",
616
+ disabled=disabled_input,
617
+ key="question_input"
618
  )
619
  with col_btn:
620
  submit_btn = st.form_submit_button("➀", disabled=disabled_input, use_container_width=True)
 
624
  with st.spinner("Thinking..."):
625
  answer, sources, error = ask_question(user_question)
626
  if answer:
 
627
  bot_msg = answer
628
  st.session_state.chat.append(("bot", bot_msg))
629
  else:
630
  st.session_state.chat.append(("bot", f"πŸ”΄ **Error:** {error}"))
631
  st.rerun()
632
 
633
+ # ---------------- CHAT HISTORY ----------------
634
  if st.session_state.chat:
635
  st.markdown("---")
636
+ st.markdown("### Chat History")
637
+
638
+ # Display in reverse order (newest first)
639
  for role, msg in reversed(st.session_state.chat):
640
  if role == "user":
641
+ st.markdown(f"<div class='chat-user'><strong>You:</strong><br>{msg}</div>", unsafe_allow_html=True)
642
  else:
643
+ st.markdown(f"<div class='chat-bot'><strong>Assistant:</strong><br>{msg}</div>", unsafe_allow_html=True)
644
+ else:
645
+ st.markdown("---")
646
+ st.info("πŸ‘ˆ Upload a PDF and start chatting!")
647
+
648
+ # ---------------- FINAL NUCLEAR OPTION ----------------
649
+ # Add one more JavaScript layer as a last resort
650
+ html("""
651
+ <script>
652
+ // Final attempt - runs after everything else
653
+ setTimeout(() => {
654
+ // Check if sidebar is visible
655
+ const sidebar = document.querySelector('[data-testid="stSidebar"]');
656
+ const mainContent = document.querySelector('.main');
657
+
658
+ if (sidebar && mainContent) {
659
+ // If sidebar exists but might be hidden by CSS
660
+ const sidebarRect = sidebar.getBoundingClientRect();
661
+ if (sidebarRect.width < 100) {
662
+ console.warn('Sidebar too narrow, forcing width');
663
+ sidebar.style.width = '20rem';
664
+ sidebar.style.minWidth = '20rem';
665
+ sidebar.style.display = 'block';
666
+
667
+ // Also adjust main content
668
+ mainContent.style.marginLeft = '20rem';
669
+ }
670
+ } else if (!sidebar && window.innerWidth > 768) {
671
+ console.error('Sidebar not found! Creating emergency sidebar');
672
+
673
+ // Create emergency sidebar container
674
+ const emergencySidebar = document.createElement('div');
675
+ emergencySidebar.id = 'emergency-sidebar-fallback';
676
+ emergencySidebar.innerHTML = `
677
+ <div style="position:fixed; left:0; top:0; width:20rem; height:100vh; background:#0e1117; z-index:999999; padding:20px; overflow-y:auto; color:white;">
678
+ <h3>πŸ“˜ PDF Assistant</h3>
679
+ <p><em>Sidebar recovery mode</em></p>
680
+ <hr>
681
+ <p>Please refresh the page (Ctrl+F5) for full functionality.</p>
682
+ <button onclick="location.reload(true)" style="background:#4CAF50; color:white; border:none; padding:10px; border-radius:5px; cursor:pointer; width:100%; margin-top:20px;">
683
+ πŸ”„ Refresh App
684
+ </button>
685
+ </div>
686
+ `;
687
+ document.body.appendChild(emergencySidebar);
688
+
689
+ // Adjust main content
690
+ if (mainContent) {
691
+ mainContent.style.marginLeft = '20rem';
692
+ }
693
+ }
694
+ }, 2000);
695
+ </script>
696
+ """, height=0)