Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -0,0 +1,99 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
from PyPDF2 import PdfReader
|
3 |
+
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
4 |
+
from langchain.embeddings import HuggingFaceEmbeddings
|
5 |
+
from langchain.vectorstores import FAISS
|
6 |
+
from langchain.llms import HuggingFaceHub
|
7 |
+
from langchain.chains import RetrievalQAWithSourcesChain
|
8 |
+
import pandas as pd
|
9 |
+
import os
|
10 |
+
import io
|
11 |
+
|
12 |
+
# --- 1. Data Loading and Preprocessing ---
|
13 |
+
|
14 |
+
@st.cache_data()
|
15 |
+
def load_and_process_pdfs_from_folder(docs_folder="docs"):
|
16 |
+
"""Loads and processes all PDF files from the specified folder."""
|
17 |
+
all_text = ""
|
18 |
+
all_tables = []
|
19 |
+
for filename in os.listdir(docs_folder):
|
20 |
+
if filename.endswith(".pdf"):
|
21 |
+
filepath = os.path.join(docs_folder, filename)
|
22 |
+
try:
|
23 |
+
with open(filepath, 'rb') as file:
|
24 |
+
pdf_reader = PdfReader(file)
|
25 |
+
for page in pdf_reader.pages:
|
26 |
+
all_text += page.extract_text() + "\n"
|
27 |
+
try:
|
28 |
+
for table in page.extract_tables():
|
29 |
+
df = pd.DataFrame(table)
|
30 |
+
all_tables.append(df)
|
31 |
+
except Exception as e:
|
32 |
+
print(f"Could not extract tables from page in {filename}. Error: {e}")
|
33 |
+
except Exception as e:
|
34 |
+
st.error(f"Error reading PDF {filename}: {e}")
|
35 |
+
return all_text, all_tables
|
36 |
+
|
37 |
+
@st.cache_data()
|
38 |
+
def split_text_into_chunks(text):
|
39 |
+
"""Splits the text into smaller, manageable chunks."""
|
40 |
+
text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=100)
|
41 |
+
chunks = text_splitter.split_text(text)
|
42 |
+
return chunks
|
43 |
+
|
44 |
+
@st.cache_data()
|
45 |
+
def create_vectorstore(chunks):
|
46 |
+
"""Creates a vectorstore from the text chunks using HuggingFace embeddings."""
|
47 |
+
embeddings = HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
|
48 |
+
vectorstore = FAISS.from_texts(chunks, embeddings)
|
49 |
+
return vectorstore
|
50 |
+
|
51 |
+
# --- 2. Question Answering with RAG ---
|
52 |
+
|
53 |
+
@st.cache_resource()
|
54 |
+
def setup_llm():
|
55 |
+
"""Sets up the Hugging Face Hub LLM."""
|
56 |
+
llm = HuggingFaceHub(repo_id="google/flan-t5-xxl", model_kwargs={"temperature": 0.5, "max_length": 512})
|
57 |
+
return llm
|
58 |
+
|
59 |
+
def perform_rag(vectorstore, llm, query):
|
60 |
+
"""Performs retrieval-augmented generation."""
|
61 |
+
qa_chain = RetrievalQAWithSourcesChain.from_llm(llm, retriever=vectorstore.as_retriever())
|
62 |
+
result = qa_chain({"question": query})
|
63 |
+
return result
|
64 |
+
|
65 |
+
# --- 3. Streamlit UI ---
|
66 |
+
|
67 |
+
def main():
|
68 |
+
st.title("PDF Q&A with Local Docs")
|
69 |
+
st.info("Make sure you have a 'docs' folder in the same directory as this script containing your PDF files.")
|
70 |
+
|
71 |
+
with st.spinner("Loading and processing PDF(s)..."):
|
72 |
+
all_text, all_tables = load_and_process_pdfs_from_folder()
|
73 |
+
|
74 |
+
if all_text:
|
75 |
+
with st.spinner("Creating knowledge base..."):
|
76 |
+
chunks = split_text_into_chunks(all_text)
|
77 |
+
vectorstore = create_vectorstore(chunks)
|
78 |
+
llm = setup_llm()
|
79 |
+
|
80 |
+
query = st.text_input("Ask a question about the documents:")
|
81 |
+
if query:
|
82 |
+
with st.spinner("Searching for answer..."):
|
83 |
+
result = perform_rag(vectorstore, llm, query)
|
84 |
+
st.subheader("Answer:")
|
85 |
+
st.write(result["answer"])
|
86 |
+
if "sources" in result:
|
87 |
+
st.subheader("Source:")
|
88 |
+
st.write(result["sources"])
|
89 |
+
|
90 |
+
if all_tables:
|
91 |
+
st.subheader("Extracted Tables:")
|
92 |
+
for i, table_df in enumerate(all_tables):
|
93 |
+
st.write(f"Table {i+1}:")
|
94 |
+
st.dataframe(table_df)
|
95 |
+
elif not all_text:
|
96 |
+
st.warning("No PDF files found in the 'docs' folder.")
|
97 |
+
|
98 |
+
if __name__ == "__main__":
|
99 |
+
main()
|