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
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
from dotenv import load_dotenv
load_dotenv()

import streamlit as st
import base64
import os


from rag_pipeline import RAGSystem  # your existing RAG pipeline

from models.groq_stt import transcribe_audio

# ================================
# OPTIONAL: VOICE TRANSCRIPTION HOOK
# ================================
def transcribe_audio(audio_file):
    """

    TODO: Connect this to a real STT backend (e.g., Groq Whisper or OpenAI Whisper).



    audio_file is a Streamlit UploadedFile from st.audio_input.

    You can get bytes via: audio_bytes = audio_file.getvalue()



    Example (pseudo-code with Groq Whisper / OpenAI-compatible):



    from openai import OpenAI

    client = OpenAI(base_url="https://api.groq.com/openai/v1", api_key=os.getenv("GROQ_API_KEY"))

    audio_bytes = audio_file.getvalue()

    with open("tmp.wav", "wb") as f:

        f.write(audio_bytes)

    resp = client.audio.transcriptions.create(

        model="whisper-large-v3-turbo",

        file=open("tmp.wav", "rb"),

        response_format="text",

        language="en"

    )

    return resp



    For now, we just show a warning and return None.

    """
    st.warning("🎀 Voice UI is ready, but STT is not wired yet. "
               "Implement transcribe_audio() using Groq Whisper or another STT API.")
    return None


# ================================
# PAGE CONFIG
# ================================
st.set_page_config(
    page_title="πŸš€ AI PDF Chat Assistant",
    layout="wide",
    page_icon="πŸ€–",
)

# ================================
# LIGHT / DARK MODE TOGGLE
# ================================
# ================================
# THEME SWITCH + SIDEBAR STYLING
# ================================
theme_choice = st.sidebar.radio("πŸŒ— Theme", ["Light", "Dark"])

# -------------------------------
# THEME COLORS
# -------------------------------
if theme_choice == "Dark":
    bg_color = "#0E0F14"              # deep black-blue background
    text_color = "#FFFFFF"            # white text
    uploader_text = "#E0E0E0"         # soft gray
    sidebar_bg = "#121212"            # premium dark sidebar
    sidebar_text = "#F5F5F5"          # bright sidebar text
else:
    bg_color = "#E8D8B8"              # clean light grey background
    text_color = "#222222"            # dark text
    uploader_text = "#444444"         # medium gray
    sidebar_bg = "#FFFFFF"            # PURE white sidebar
    sidebar_text = "#222222"          # dark gray text for readability

# -------------------------------
# APPLY THEME CSS
# -------------------------------
st.markdown(f"""

<style>



/* ----------- MAIN BACKGROUND ----------- */

html, body, .stApp {{

    background-color: {bg_color} !important;

    color: {text_color} !important;

}}



/* ----------- SIDEBAR BACKGROUND ----------- */

[data-testid="stSidebar"] > div:first-child {{

    background-color: {sidebar_bg} !important;

    color: {sidebar_text} !important;

    border-right: 1px solid #44444422;

}}



/* ----------- SIDEBAR TEXT ----------- */

[data-testid="stSidebar"] * {{

    color: {sidebar_text} !important;

    font-weight: 500;

}}



/* ----------- PDF UPLOADER TEXT ----------- */

.upload-text {{

    color: {uploader_text} !important;

}}



/* Buttons look cleaner */

.stButton>button {{

    background-color: #3A77FF !important;

    color: white !important;

    border-radius: 10px !important;

    border: none !important;

}}



</style>

""", unsafe_allow_html=True)



# ================================
# FIX FILE UPLOADER TEXT COLOR
# ================================
st.markdown(f"""

<style>

div[data-testid="stFileUploader"] label {{

    color: {uploader_text} !important;

    font-size: 15px !important;

    font-weight: 600 !important;

}}



div[data-testid="stFileUploader"] p {{

    color: {uploader_text} !important;

    opacity: 0.85 !important;

}}

</style>

""", unsafe_allow_html=True)

# ================================
# FIX SIDEBAR COLLAPSE BUTTON & CLEAR CHAT TEXT
# ================================
st.markdown("""

<style>

button[kind="secondary"] svg {

    color: white !important;

    stroke: white !important;

}



button[kind="secondary"] {

    background: rgba(255,255,255,0.2) !important;

    border-radius: 10px !important;

}



/* Base button labels (affects Clear Chat, etc.) */

button[data-testid="baseButton-label"] {

    color: white !important;

    font-weight: 600 !important;

}

</style>

""", unsafe_allow_html=True)

# ================================
# PREMIUM UI CSS (CHAT + ANIMATIONS)
# ================================
st.markdown("""

<style>

.fade-in {

    animation: fadeIn 0.45s ease-in-out;

}

@keyframes fadeIn {

    from { opacity: 0; transform: translateY(6px); }

    to { opacity: 1; transform: translateY(0); }

}



/* Chat bubbles */

.chat-bubble-user {

    background-color: #0066FF;

    color: white;

    padding: 12px 16px;

    border-radius: 16px;

    max-width: 80%;

    margin-bottom: 10px;

}

.chat-bubble-assistant {

    background-color: #262730;

    color: white;

    padding: 12px 16px;

    border-radius: 16px;

    max-width: 80%;

    margin-bottom: 10px;

}



/* Floating Chat Input */

.stChatInputContainer {

    position: fixed !important;

    bottom: 20px !important;

    width: 65% !important;

    left: 30% !important;

    z-index: 9999 !important;

}



/* Sidebar card */

.sidebar-box {

    background: #1e1f26;

    padding: 20px;

    border-radius: 16px;

    color: white;

    box-shadow: 0px 4px 12px rgba(0,0,0,0.35);

}

</style>

""", unsafe_allow_html=True)

# ================================
# HEADER
# ================================
st.markdown(f"""

<div style="text-align:center; padding: 8px 0 20px 0;">

    <h1 style="color:{text_color};">πŸ€– AI Document Chat Assistant</h1>

    <p style="font-size:18px; color:{text_color}; opacity:0.8;">

        Upload multiple PDFs β†’ Process β†’ Auto-summarize β†’ Chat using <b>Groq LLaMA-3.3-70B</b>

    </p>

</div>

""", unsafe_allow_html=True)

# ================================
# SESSION STATE: MULTI-PDF + RAG + CHAT
# ================================
if "pdf_docs" not in st.session_state:
    # doc_id -> {name, path, indexed: bool}
    st.session_state.pdf_docs = {}

if "rags" not in st.session_state:
    # doc_id -> RAGSystem()
    st.session_state.rags = {}

if "chat_histories" not in st.session_state:
    # doc_id -> list of {"role": "user"/"assistant", "content": str}
    st.session_state.chat_histories = {}

if "summaries" not in st.session_state:
    # doc_id -> summary text
    st.session_state.summaries = {}

# ================================
# LAYOUT
# ================================
left, right = st.columns([1.2, 2.8])

# ================================
# LEFT PANEL β€” MULTI PDF UPLOAD
# ================================
with left:
    st.markdown("<div class='sidebar-box'>", unsafe_allow_html=True)
    st.subheader("πŸ“‚ Upload PDFs")

    uploaded_pdfs = st.file_uploader(
        "Drag & drop one or more PDFs",
        type=["pdf"],
        accept_multiple_files=True
    )

    if uploaded_pdfs:
        os.makedirs("data", exist_ok=True)

        for f in uploaded_pdfs:
            doc_id = f.name  # simple key by filename
            save_path = os.path.join("data", f.name)

            # Save file to disk
            with open(save_path, "wb") as out:
                out.write(f.read())

            # Register in session_state if not present
            if doc_id not in st.session_state.pdf_docs:
                st.session_state.pdf_docs[doc_id] = {
                    "name": f.name,
                    "path": save_path,
                    "indexed": False,
                }
                st.session_state.rags[doc_id] = RAGSystem()
                st.session_state.chat_histories[doc_id] = []
                st.session_state.summaries[doc_id] = None

        st.success(f"πŸ“„ Uploaded {len(uploaded_pdfs)} file(s)!")

    # List docs
    if st.session_state.pdf_docs:
        st.markdown("### πŸ“ Available PDFs")
        for doc_id, meta in st.session_state.pdf_docs.items():
            status = "βœ… Indexed" if meta.get("indexed") else "⏳ Not indexed"
            st.write(f"- **{meta['name']}** β€” {status}")
    else:
        st.info("No PDFs uploaded yet.")

    # Global clear chats
    if st.button("🧹 Clear All Chats", use_container_width=True):
        for k in st.session_state.chat_histories:
            st.session_state.chat_histories[k] = []
        st.toast("All chats cleared!")

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

# ================================
# RIGHT PANEL β€” ACTIVE DOC + CHAT
# ================================
with right:
    if not st.session_state.pdf_docs:
        st.info("πŸ“₯ Upload one or more PDFs on the left to get started.")
    else:
        # "Tabs" style selector using horizontal radio
        doc_ids = list(st.session_state.pdf_docs.keys())

        active_doc_id = st.radio(
            "πŸ—‚ Active document",
            options=doc_ids,
            format_func=lambda x: "πŸ“„ " + st.session_state.pdf_docs[x]["name"],
            horizontal=True,
        )

        active_meta = st.session_state.pdf_docs[active_doc_id]
        active_rag = st.session_state.rags[active_doc_id]
        active_chat = st.session_state.chat_histories[active_doc_id]

        st.markdown(f"### πŸ“„ {active_meta['name']}")

        # ============================
        # PDF PREVIEW (CHROME-SAFE VIEWER)
        # ============================
        try:
            with open(active_meta["path"], "rb") as f:
                pdf_bytes = f.read()

            b64 = base64.b64encode(pdf_bytes).decode("utf-8")

            pdf_viewer = f"""

                <embed 

                    src="data:application/pdf;base64,{b64}"

                    type="application/pdf"

                    width="100%"

                    height="500px"

                    style="border-radius:12px; border:1px solid #555;">

            """

            st.markdown(pdf_viewer, unsafe_allow_html=True)

        except FileNotFoundError:
            st.error("PDF file not found on disk. Try re-uploading.")


# ---- Buttons Row: Process + Summarize ----
col1, col2 = st.columns(2)

with col1:
    if st.button("πŸš€ Process this PDF", key=f"process_{active_doc_id}", use_container_width=True):
        with st.spinner("Extracting text, tables & OCR, building index…"):
            active_rag.ingest_pdf(active_meta["path"])
        active_meta["indexed"] = True
        st.success("✨ PDF processed & indexed!")

with col2:
    if not active_meta.get("indexed"):
        st.button("🧠 Auto-summarize PDF", key=f"summarize_{active_doc_id}",
                  disabled=True, use_container_width=True)
        st.caption("⚠ Process the PDF first to enable summarization.")
    else:
        if st.button("🧠 Auto-summarize PDF", key=f"summarize_{active_doc_id}",
                     use_container_width=True):
            with st.spinner("Generating summary from the document…"):
                summary, _ = active_rag.query(
                    "Give a detailed, structured summary of this document with headings."
                )
            st.session_state.summaries[active_doc_id] = summary
            st.success("πŸ“˜ Summary generated!")


        # Show summary if exists
        if st.session_state.summaries.get(active_doc_id):
            st.markdown("#### πŸ“˜ Document Summary")
            st.markdown(st.session_state.summaries[active_doc_id])

        st.markdown("---")
        st.subheader("πŸ’¬ Chat with this document")

        # Show chat history for active doc
        for msg in active_chat:
            role = msg["role"]
            bubble = "chat-bubble-user" if role == "user" else "chat-bubble-assistant"
            st.chat_message("user" if role == "user" else "assistant").markdown(
                f"<div class='{bubble} fade-in'>{msg['content']}</div>",
                unsafe_allow_html=True,
            )
# ============================
# CHAT INPUT + MICROPHONE (AUTO-TRANSCRIBE)
# ============================

# 1️⃣ Always show audio recorder β€” it activates recording
audio = st.audio_input("πŸŽ™ Speak your question")

col1, col2 = st.columns([9, 1])

with col1:
    user_input = st.chat_input(f"Ask a question about: {active_meta['name']}")

# 2️⃣ Mic button is optional (visual only)
with col2:
    st.write("")  # spacing
    st.write("")
   

# 3️⃣ If user finished recording β†’ auto-transcribe
if audio is not None:
    with st.spinner("Transcribing your voice..."):
        spoken_text = active_rag.llm.transcribe_audio(audio.getvalue())

    if spoken_text:
        st.success(f"🎀 You said: **{spoken_text}**")
        user_input = spoken_text  # auto-send as chat message


# ============================
# PROCESS USER TEXT MESSAGE
# ============================
if user_input:
    # Add user message
    active_chat.append({"role": "user", "content": user_input})
    st.chat_message("user").markdown(
        f"<div class='chat-bubble-user fade-in'>{user_input}</div>",
        unsafe_allow_html=True,
    )

    # Prevent queries before indexing
    if not active_meta.get("indexed"):
        st.warning("⚠️ Please process this PDF first (πŸš€ Process this PDF).")
    else:
        # Typing animation
        typing = st.chat_message("assistant")
        typing.markdown(
            "<div class='chat-bubble-assistant'>Typing...</div>",
            unsafe_allow_html=True,
        )

        # Run RAG pipeline
        with st.spinner("Analyzing document..."):
            answer, citations = active_rag.query(user_input)

        typing.empty()

        # Build assistant final reply
        final_reply = (
            f"{answer}\n\nπŸ“Œ **Sources:**\n" +
            "\n".join([f"- {c}" for c in citations])
        )

        active_chat.append({"role": "assistant", "content": final_reply})

        st.chat_message("assistant").markdown(
            f"<div class='chat-bubble-assistant fade-in'>{final_reply}</div>",
            unsafe_allow_html=True,
        )