prd-reader / src /streamlit_main.py
shiva232's picture
Rename src/streamlit_app.py to src/streamlit_main.py
1cdb2b8 verified
Raw History Blame Contribute Delete
3.81 kB
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.")