File size: 3,814 Bytes
25cc735
f555f9f
25cc735
f555f9f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
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.")