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""" """, unsafe_allow_html=True) # ================================ # FIX FILE UPLOADER TEXT COLOR # ================================ st.markdown(f""" """, unsafe_allow_html=True) # ================================ # FIX SIDEBAR COLLAPSE BUTTON & CLEAR CHAT TEXT # ================================ st.markdown(""" """, unsafe_allow_html=True) # ================================ # PREMIUM UI CSS (CHAT + ANIMATIONS) # ================================ st.markdown(""" """, unsafe_allow_html=True) # ================================ # HEADER # ================================ st.markdown(f"""

πŸ€– AI Document Chat Assistant

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

""", 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("", 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""" """ 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"
{msg['content']}
", 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"
{user_input}
", 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( "
Typing...
", 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"
{final_reply}
", unsafe_allow_html=True, )