import streamlit as st from PyPDF2 import PdfReader # ✅ Updated LangChain imports from langchain_text_splitters import RecursiveCharacterTextSplitter from langchain_community.embeddings import HuggingFaceEmbeddings from langchain_community.vectorstores import FAISS from transformers import pipeline # ------------------------------- # PAGE CONFIG # ------------------------------- st.set_page_config( page_title="Multi-PDF Chat Agent", page_icon="📄", layout="wide" ) st.title("📄 Multi-PDF Chat Agent") st.caption("Upload PDFs and ask questions from them") # ------------------------------- # SESSION STATE # ------------------------------- if "vector_store" not in st.session_state: st.session_state.vector_store = None # ------------------------------- # LOAD QA MODEL (FIXED) # ------------------------------- @st.cache_resource def load_qa_pipeline(): return pipeline( "question-answering", model="distilbert-base-cased-distilled-squad" ) qa_pipeline = load_qa_pipeline() # ------------------------------- # SIDEBAR # ------------------------------- with st.sidebar: st.header("📂 Upload PDFs") uploaded_files = st.file_uploader( "Upload one or more PDF files", type="pdf", accept_multiple_files=True ) if st.button("⚡ Process PDFs"): if not uploaded_files: st.warning("Please upload at least one PDF.") else: with st.spinner("Processing documents..."): text = "" # ✅ Extract text safely for file in uploaded_files: pdf_reader = PdfReader(file) for page in pdf_reader.pages: page_text = page.extract_text() if page_text: text += page_text if not text.strip(): st.error("No readable text found in PDFs.") else: # ✅ Split text splitter = RecursiveCharacterTextSplitter( chunk_size=800, chunk_overlap=100 ) chunks = splitter.split_text(text) # ✅ Embeddings embeddings = HuggingFaceEmbeddings( model_name="sentence-transformers/all-MiniLM-L6-v2" ) # ✅ Vector store vector_store = FAISS.from_texts( texts=chunks, embedding=embeddings ) st.session_state.vector_store = vector_store st.success("✅ PDFs processed successfully!") # ------------------------------- # MAIN CHAT # ------------------------------- if st.session_state.vector_store: st.subheader("💬 Ask Questions") question = st.text_input( "Enter your question:", placeholder="What is the main topic?" ) if question: with st.spinner("Thinking..."): # ✅ Retrieve relevant chunks docs = st.session_state.vector_store.similarity_search( question, k=2 # reduced for HF memory safety ) context = "\n".join([doc.page_content for doc in docs]) # ✅ Get answer result = qa_pipeline( question=question, context=context ) st.markdown("### ✅ Answer") st.write(result["answer"]) st.markdown("### 📚 Source Excerpts") for i, doc in enumerate(docs): st.markdown(f"**Excerpt {i+1}:**") st.write(doc.page_content) else: st.info("👈 Upload and process PDFs to begin.")