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
 
 
 
 
 
 
1
+ from dotenv import load_dotenv
2
+ load_dotenv()
3
+
4
+ import streamlit as st
5
+ import base64
6
+ import os
7
+
8
+
9
+ from rag_pipeline import RAGSystem # your existing RAG pipeline
10
+
11
+ from models.groq_stt import transcribe_audio
12
+
13
+ # ================================
14
+ # OPTIONAL: VOICE TRANSCRIPTION HOOK
15
+ # ================================
16
+ def transcribe_audio(audio_file):
17
+ """
18
+ TODO: Connect this to a real STT backend (e.g., Groq Whisper or OpenAI Whisper).
19
+
20
+ audio_file is a Streamlit UploadedFile from st.audio_input.
21
+ You can get bytes via: audio_bytes = audio_file.getvalue()
22
+
23
+ Example (pseudo-code with Groq Whisper / OpenAI-compatible):
24
+
25
+ from openai import OpenAI
26
+ client = OpenAI(base_url="https://api.groq.com/openai/v1", api_key=os.getenv("GROQ_API_KEY"))
27
+ audio_bytes = audio_file.getvalue()
28
+ with open("tmp.wav", "wb") as f:
29
+ f.write(audio_bytes)
30
+ resp = client.audio.transcriptions.create(
31
+ model="whisper-large-v3-turbo",
32
+ file=open("tmp.wav", "rb"),
33
+ response_format="text",
34
+ language="en"
35
+ )
36
+ return resp
37
+
38
+ For now, we just show a warning and return None.
39
+ """
40
+ st.warning("🎀 Voice UI is ready, but STT is not wired yet. "
41
+ "Implement transcribe_audio() using Groq Whisper or another STT API.")
42
+ return None
43
+
44
+
45
+ # ================================
46
+ # PAGE CONFIG
47
+ # ================================
48
+ st.set_page_config(
49
+ page_title="πŸš€ AI PDF Chat Assistant",
50
+ layout="wide",
51
+ page_icon="πŸ€–",
52
+ )
53
+
54
+ # ================================
55
+ # LIGHT / DARK MODE TOGGLE
56
+ # ================================
57
+ # ================================
58
+ # THEME SWITCH + SIDEBAR STYLING
59
+ # ================================
60
+ theme_choice = st.sidebar.radio("πŸŒ— Theme", ["Light", "Dark"])
61
+
62
+ # -------------------------------
63
+ # THEME COLORS
64
+ # -------------------------------
65
+ if theme_choice == "Dark":
66
+ bg_color = "#0E0F14" # deep black-blue background
67
+ text_color = "#FFFFFF" # white text
68
+ uploader_text = "#E0E0E0" # soft gray
69
+ sidebar_bg = "#121212" # premium dark sidebar
70
+ sidebar_text = "#F5F5F5" # bright sidebar text
71
+ else:
72
+ bg_color = "#E8D8B8" # clean light grey background
73
+ text_color = "#222222" # dark text
74
+ uploader_text = "#444444" # medium gray
75
+ sidebar_bg = "#FFFFFF" # PURE white sidebar
76
+ sidebar_text = "#222222" # dark gray text for readability
77
+
78
+ # -------------------------------
79
+ # APPLY THEME CSS
80
+ # -------------------------------
81
+ st.markdown(f"""
82
+ <style>
83
+
84
+ /* ----------- MAIN BACKGROUND ----------- */
85
+ html, body, .stApp {{
86
+ background-color: {bg_color} !important;
87
+ color: {text_color} !important;
88
+ }}
89
+
90
+ /* ----------- SIDEBAR BACKGROUND ----------- */
91
+ [data-testid="stSidebar"] > div:first-child {{
92
+ background-color: {sidebar_bg} !important;
93
+ color: {sidebar_text} !important;
94
+ border-right: 1px solid #44444422;
95
+ }}
96
+
97
+ /* ----------- SIDEBAR TEXT ----------- */
98
+ [data-testid="stSidebar"] * {{
99
+ color: {sidebar_text} !important;
100
+ font-weight: 500;
101
+ }}
102
+
103
+ /* ----------- PDF UPLOADER TEXT ----------- */
104
+ .upload-text {{
105
+ color: {uploader_text} !important;
106
+ }}
107
+
108
+ /* Buttons look cleaner */
109
+ .stButton>button {{
110
+ background-color: #3A77FF !important;
111
+ color: white !important;
112
+ border-radius: 10px !important;
113
+ border: none !important;
114
+ }}
115
+
116
+ </style>
117
+ """, unsafe_allow_html=True)
118
+
119
+
120
+
121
+ # ================================
122
+ # FIX FILE UPLOADER TEXT COLOR
123
+ # ================================
124
+ st.markdown(f"""
125
+ <style>
126
+ div[data-testid="stFileUploader"] label {{
127
+ color: {uploader_text} !important;
128
+ font-size: 15px !important;
129
+ font-weight: 600 !important;
130
+ }}
131
+
132
+ div[data-testid="stFileUploader"] p {{
133
+ color: {uploader_text} !important;
134
+ opacity: 0.85 !important;
135
+ }}
136
+ </style>
137
+ """, unsafe_allow_html=True)
138
+
139
+ # ================================
140
+ # FIX SIDEBAR COLLAPSE BUTTON & CLEAR CHAT TEXT
141
+ # ================================
142
+ st.markdown("""
143
+ <style>
144
+ button[kind="secondary"] svg {
145
+ color: white !important;
146
+ stroke: white !important;
147
+ }
148
+
149
+ button[kind="secondary"] {
150
+ background: rgba(255,255,255,0.2) !important;
151
+ border-radius: 10px !important;
152
+ }
153
+
154
+ /* Base button labels (affects Clear Chat, etc.) */
155
+ button[data-testid="baseButton-label"] {
156
+ color: white !important;
157
+ font-weight: 600 !important;
158
+ }
159
+ </style>
160
+ """, unsafe_allow_html=True)
161
+
162
+ # ================================
163
+ # PREMIUM UI CSS (CHAT + ANIMATIONS)
164
+ # ================================
165
+ st.markdown("""
166
+ <style>
167
+ .fade-in {
168
+ animation: fadeIn 0.45s ease-in-out;
169
+ }
170
+ @keyframes fadeIn {
171
+ from { opacity: 0; transform: translateY(6px); }
172
+ to { opacity: 1; transform: translateY(0); }
173
+ }
174
+
175
+ /* Chat bubbles */
176
+ .chat-bubble-user {
177
+ background-color: #0066FF;
178
+ color: white;
179
+ padding: 12px 16px;
180
+ border-radius: 16px;
181
+ max-width: 80%;
182
+ margin-bottom: 10px;
183
+ }
184
+ .chat-bubble-assistant {
185
+ background-color: #262730;
186
+ color: white;
187
+ padding: 12px 16px;
188
+ border-radius: 16px;
189
+ max-width: 80%;
190
+ margin-bottom: 10px;
191
+ }
192
+
193
+ /* Floating Chat Input */
194
+ .stChatInputContainer {
195
+ position: fixed !important;
196
+ bottom: 20px !important;
197
+ width: 65% !important;
198
+ left: 30% !important;
199
+ z-index: 9999 !important;
200
+ }
201
+
202
+ /* Sidebar card */
203
+ .sidebar-box {
204
+ background: #1e1f26;
205
+ padding: 20px;
206
+ border-radius: 16px;
207
+ color: white;
208
+ box-shadow: 0px 4px 12px rgba(0,0,0,0.35);
209
+ }
210
+ </style>
211
+ """, unsafe_allow_html=True)
212
+
213
+ # ================================
214
+ # HEADER
215
+ # ================================
216
+ st.markdown(f"""
217
+ <div style="text-align:center; padding: 8px 0 20px 0;">
218
+ <h1 style="color:{text_color};">πŸ€– AI Document Chat Assistant</h1>
219
+ <p style="font-size:18px; color:{text_color}; opacity:0.8;">
220
+ Upload multiple PDFs β†’ Process β†’ Auto-summarize β†’ Chat using <b>Groq LLaMA-3.3-70B</b>
221
+ </p>
222
+ </div>
223
+ """, unsafe_allow_html=True)
224
+
225
+ # ================================
226
+ # SESSION STATE: MULTI-PDF + RAG + CHAT
227
+ # ================================
228
+ if "pdf_docs" not in st.session_state:
229
+ # doc_id -> {name, path, indexed: bool}
230
+ st.session_state.pdf_docs = {}
231
+
232
+ if "rags" not in st.session_state:
233
+ # doc_id -> RAGSystem()
234
+ st.session_state.rags = {}
235
+
236
+ if "chat_histories" not in st.session_state:
237
+ # doc_id -> list of {"role": "user"/"assistant", "content": str}
238
+ st.session_state.chat_histories = {}
239
+
240
+ if "summaries" not in st.session_state:
241
+ # doc_id -> summary text
242
+ st.session_state.summaries = {}
243
+
244
+ # ================================
245
+ # LAYOUT
246
+ # ================================
247
+ left, right = st.columns([1.2, 2.8])
248
+
249
+ # ================================
250
+ # LEFT PANEL β€” MULTI PDF UPLOAD
251
+ # ================================
252
+ with left:
253
+ st.markdown("<div class='sidebar-box'>", unsafe_allow_html=True)
254
+ st.subheader("πŸ“‚ Upload PDFs")
255
+
256
+ uploaded_pdfs = st.file_uploader(
257
+ "Drag & drop one or more PDFs",
258
+ type=["pdf"],
259
+ accept_multiple_files=True
260
+ )
261
+
262
+ if uploaded_pdfs:
263
+ os.makedirs("data", exist_ok=True)
264
+
265
+ for f in uploaded_pdfs:
266
+ doc_id = f.name # simple key by filename
267
+ save_path = os.path.join("data", f.name)
268
+
269
+ # Save file to disk
270
+ with open(save_path, "wb") as out:
271
+ out.write(f.read())
272
+
273
+ # Register in session_state if not present
274
+ if doc_id not in st.session_state.pdf_docs:
275
+ st.session_state.pdf_docs[doc_id] = {
276
+ "name": f.name,
277
+ "path": save_path,
278
+ "indexed": False,
279
+ }
280
+ st.session_state.rags[doc_id] = RAGSystem()
281
+ st.session_state.chat_histories[doc_id] = []
282
+ st.session_state.summaries[doc_id] = None
283
+
284
+ st.success(f"πŸ“„ Uploaded {len(uploaded_pdfs)} file(s)!")
285
+
286
+ # List docs
287
+ if st.session_state.pdf_docs:
288
+ st.markdown("### πŸ“ Available PDFs")
289
+ for doc_id, meta in st.session_state.pdf_docs.items():
290
+ status = "βœ… Indexed" if meta.get("indexed") else "⏳ Not indexed"
291
+ st.write(f"- **{meta['name']}** β€” {status}")
292
+ else:
293
+ st.info("No PDFs uploaded yet.")
294
+
295
+ # Global clear chats
296
+ if st.button("🧹 Clear All Chats", use_container_width=True):
297
+ for k in st.session_state.chat_histories:
298
+ st.session_state.chat_histories[k] = []
299
+ st.toast("All chats cleared!")
300
+
301
+ st.markdown("</div>", unsafe_allow_html=True)
302
+
303
+ # ================================
304
+ # RIGHT PANEL β€” ACTIVE DOC + CHAT
305
+ # ================================
306
+ with right:
307
+ if not st.session_state.pdf_docs:
308
+ st.info("πŸ“₯ Upload one or more PDFs on the left to get started.")
309
+ else:
310
+ # "Tabs" style selector using horizontal radio
311
+ doc_ids = list(st.session_state.pdf_docs.keys())
312
+
313
+ active_doc_id = st.radio(
314
+ "πŸ—‚ Active document",
315
+ options=doc_ids,
316
+ format_func=lambda x: "πŸ“„ " + st.session_state.pdf_docs[x]["name"],
317
+ horizontal=True,
318
+ )
319
+
320
+ active_meta = st.session_state.pdf_docs[active_doc_id]
321
+ active_rag = st.session_state.rags[active_doc_id]
322
+ active_chat = st.session_state.chat_histories[active_doc_id]
323
+
324
+ st.markdown(f"### πŸ“„ {active_meta['name']}")
325
+
326
+ # ============================
327
+ # PDF PREVIEW (CHROME-SAFE VIEWER)
328
+ # ============================
329
+ try:
330
+ with open(active_meta["path"], "rb") as f:
331
+ pdf_bytes = f.read()
332
+
333
+ b64 = base64.b64encode(pdf_bytes).decode("utf-8")
334
+
335
+ pdf_viewer = f"""
336
+ <embed
337
+ src="data:application/pdf;base64,{b64}"
338
+ type="application/pdf"
339
+ width="100%"
340
+ height="500px"
341
+ style="border-radius:12px; border:1px solid #555;">
342
+ """
343
+
344
+ st.markdown(pdf_viewer, unsafe_allow_html=True)
345
+
346
+ except FileNotFoundError:
347
+ st.error("PDF file not found on disk. Try re-uploading.")
348
+
349
+
350
+ # ---- Buttons Row: Process + Summarize ----
351
+ col1, col2 = st.columns(2)
352
+
353
+ with col1:
354
+ if st.button("πŸš€ Process this PDF", key=f"process_{active_doc_id}", use_container_width=True):
355
+ with st.spinner("Extracting text, tables & OCR, building index…"):
356
+ active_rag.ingest_pdf(active_meta["path"])
357
+ active_meta["indexed"] = True
358
+ st.success("✨ PDF processed & indexed!")
359
+
360
+ with col2:
361
+ if not active_meta.get("indexed"):
362
+ st.button("🧠 Auto-summarize PDF", key=f"summarize_{active_doc_id}",
363
+ disabled=True, use_container_width=True)
364
+ st.caption("⚠ Process the PDF first to enable summarization.")
365
+ else:
366
+ if st.button("🧠 Auto-summarize PDF", key=f"summarize_{active_doc_id}",
367
+ use_container_width=True):
368
+ with st.spinner("Generating summary from the document…"):
369
+ summary, _ = active_rag.query(
370
+ "Give a detailed, structured summary of this document with headings."
371
+ )
372
+ st.session_state.summaries[active_doc_id] = summary
373
+ st.success("πŸ“˜ Summary generated!")
374
+
375
+
376
+ # Show summary if exists
377
+ if st.session_state.summaries.get(active_doc_id):
378
+ st.markdown("#### πŸ“˜ Document Summary")
379
+ st.markdown(st.session_state.summaries[active_doc_id])
380
+
381
+ st.markdown("---")
382
+ st.subheader("πŸ’¬ Chat with this document")
383
+
384
+ # Show chat history for active doc
385
+ for msg in active_chat:
386
+ role = msg["role"]
387
+ bubble = "chat-bubble-user" if role == "user" else "chat-bubble-assistant"
388
+ st.chat_message("user" if role == "user" else "assistant").markdown(
389
+ f"<div class='{bubble} fade-in'>{msg['content']}</div>",
390
+ unsafe_allow_html=True,
391
+ )
392
+ # ============================
393
+ # CHAT INPUT + MICROPHONE (AUTO-TRANSCRIBE)
394
+ # ============================
395
+
396
+ # 1️⃣ Always show audio recorder β€” it activates recording
397
+ audio = st.audio_input("πŸŽ™ Speak your question")
398
+
399
+ col1, col2 = st.columns([9, 1])
400
+
401
+ with col1:
402
+ user_input = st.chat_input(f"Ask a question about: {active_meta['name']}")
403
+
404
+ # 2️⃣ Mic button is optional (visual only)
405
+ with col2:
406
+ st.write("") # spacing
407
+ st.write("")
408
+
409
+
410
+ # 3️⃣ If user finished recording β†’ auto-transcribe
411
+ if audio is not None:
412
+ with st.spinner("Transcribing your voice..."):
413
+ spoken_text = active_rag.llm.transcribe_audio(audio.getvalue())
414
+
415
+ if spoken_text:
416
+ st.success(f"🎀 You said: **{spoken_text}**")
417
+ user_input = spoken_text # auto-send as chat message
418
+
419
+
420
+ # ============================
421
+ # PROCESS USER TEXT MESSAGE
422
+ # ============================
423
+ if user_input:
424
+ # Add user message
425
+ active_chat.append({"role": "user", "content": user_input})
426
+ st.chat_message("user").markdown(
427
+ f"<div class='chat-bubble-user fade-in'>{user_input}</div>",
428
+ unsafe_allow_html=True,
429
+ )
430
+
431
+ # Prevent queries before indexing
432
+ if not active_meta.get("indexed"):
433
+ st.warning("⚠️ Please process this PDF first (πŸš€ Process this PDF).")
434
+ else:
435
+ # Typing animation
436
+ typing = st.chat_message("assistant")
437
+ typing.markdown(
438
+ "<div class='chat-bubble-assistant'>Typing...</div>",
439
+ unsafe_allow_html=True,
440
+ )
441
+
442
+ # Run RAG pipeline
443
+ with st.spinner("Analyzing document..."):
444
+ answer, citations = active_rag.query(user_input)
445
+
446
+ typing.empty()
447
+
448
+ # Build assistant final reply
449
+ final_reply = (
450
+ f"{answer}\n\nπŸ“Œ **Sources:**\n" +
451
+ "\n".join([f"- {c}" for c in citations])
452
+ )
453
+
454
+ active_chat.append({"role": "assistant", "content": final_reply})
455
+
456
+ st.chat_message("assistant").markdown(
457
+ f"<div class='chat-bubble-assistant fade-in'>{final_reply}</div>",
458
+ unsafe_allow_html=True,
459
+ )
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ streamlit
2
+ python-dotenv
3
+ groq
4
+ httpx
5
+ sentence-transformers
6
+ faiss-cpu
7
+ pdfplumber
8
+ pytesseract
9
+ Pillow
10
+ opencv-python-headless
11
+ numpy
12
+ pandas
13
+ uvicorn
14
+ fastapi