pdf / app.py
haresh15's picture
Upload 2 files
2069ea6 verified
Raw History Blame Contribute Delete
14.5 kB
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,
)