Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,127 +1,118 @@
|
|
| 1 |
import os
|
| 2 |
-
import shutil
|
| 3 |
-
import tempfile
|
| 4 |
-
import fitz # PyMuPDF
|
| 5 |
import streamlit as st
|
| 6 |
-
import
|
| 7 |
-
|
|
|
|
| 8 |
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
| 9 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
|
|
|
| 10 |
from langchain_community.vectorstores import Chroma
|
| 11 |
-
from langchain_community.embeddings import SentenceTransformerEmbeddings
|
| 12 |
from langchain.chains import RetrievalQA
|
| 13 |
from langchain_community.llms import HuggingFacePipeline
|
| 14 |
from langchain.prompts import PromptTemplate
|
| 15 |
-
from langchain_community.document_loaders import TextLoader
|
| 16 |
-
|
| 17 |
-
# --- Streamlit Config ---
|
| 18 |
-
st.set_page_config(page_title="π RAG PDF Chatbot", layout="wide")
|
| 19 |
-
st.title("π RAG-based PDF Chatbot")
|
| 20 |
|
| 21 |
-
# ---
|
| 22 |
-
|
|
|
|
| 23 |
|
| 24 |
-
# --- Load
|
| 25 |
@st.cache_resource
|
| 26 |
-
def
|
| 27 |
checkpoint = "MBZUAI/LaMini-T5-738M"
|
| 28 |
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
|
| 29 |
model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
|
| 30 |
pipe = pipeline("text2text-generation", model=model, tokenizer=tokenizer, max_length=512)
|
| 31 |
return HuggingFacePipeline(pipeline=pipe)
|
| 32 |
|
| 33 |
-
# ---
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 35 |
try:
|
| 36 |
-
doc = fitz.open(stream=
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
| 38 |
except Exception as e:
|
| 39 |
-
|
| 40 |
return ""
|
| 41 |
|
| 42 |
-
# ---
|
| 43 |
-
def
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 51 |
input_variables=["context", "question"],
|
| 52 |
-
template=
|
| 53 |
-
You are a helpful assistant.
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
Question:
|
| 59 |
-
{question}
|
| 60 |
-
|
| 61 |
-
Helpful Answer:
|
| 62 |
-
"""
|
| 63 |
)
|
| 64 |
-
return RetrievalQA.from_chain_type(llm=llm, retriever=retriever, chain_type_kwargs={"prompt": prompt_template})
|
| 65 |
|
| 66 |
-
# ---
|
| 67 |
-
def
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
f.write(full_text)
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
| 74 |
|
| 75 |
-
|
| 76 |
-
chunks = text_splitter.split_documents(docs)
|
| 77 |
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
|
| 83 |
-
qa = build_qa_chain(retriever, llm)
|
| 84 |
-
return qa.run(question)
|
| 85 |
|
| 86 |
-
# ---
|
| 87 |
with st.sidebar:
|
| 88 |
-
st.header("π Upload
|
| 89 |
-
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
full_text = extract_text_from_pdf(uploaded_file)
|
| 95 |
|
| 96 |
if full_text:
|
| 97 |
-
with st.expander("π
|
| 98 |
st.write(full_text[:3000] + ("..." if len(full_text) > 3000 else ""))
|
| 99 |
|
| 100 |
-
st.
|
| 101 |
-
user_question = st.text_input("Ask a question about the document")
|
| 102 |
|
| 103 |
-
if
|
| 104 |
-
with st.spinner("
|
| 105 |
-
|
| 106 |
-
answer = process_question(user_question, full_text)
|
| 107 |
-
except Exception as e:
|
| 108 |
-
st.error("β οΈ Something went wrong. Try re-uploading the PDF.")
|
| 109 |
-
st.stop()
|
| 110 |
st.markdown("### π€ Answer")
|
| 111 |
st.write(answer)
|
| 112 |
-
|
| 113 |
-
with st.sidebar:
|
| 114 |
-
st.markdown("---")
|
| 115 |
-
st.caption("π‘ Sample Questions")
|
| 116 |
-
st.markdown("""
|
| 117 |
-
- "Summarize the document"
|
| 118 |
-
- "What is the experience of Pradeep Singh Sengar?"
|
| 119 |
-
- "What are the key points?"
|
| 120 |
-
- "Explain in short"
|
| 121 |
-
""")
|
| 122 |
else:
|
| 123 |
-
st.error("
|
| 124 |
else:
|
| 125 |
-
st.info("Upload a PDF to
|
| 126 |
-
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
|
|
|
| 2 |
import streamlit as st
|
| 3 |
+
import fitz # PyMuPDF
|
| 4 |
+
import tempfile
|
| 5 |
+
import shutil
|
| 6 |
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline
|
| 7 |
from langchain.text_splitter import RecursiveCharacterTextSplitter
|
| 8 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
| 9 |
from langchain_community.vectorstores import Chroma
|
|
|
|
| 10 |
from langchain.chains import RetrievalQA
|
| 11 |
from langchain_community.llms import HuggingFacePipeline
|
| 12 |
from langchain.prompts import PromptTemplate
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
+
# --- Streamlit Setup ---
|
| 15 |
+
st.set_page_config(page_title="π Accurate RAG PDF Chatbot", layout="wide")
|
| 16 |
+
st.title("π Accurate RAG-based PDF Chatbot")
|
| 17 |
|
| 18 |
+
# --- Load LLM (You can swap with Phi-2 or Mistral 7B later) ---
|
| 19 |
@st.cache_resource
|
| 20 |
+
def load_llm():
|
| 21 |
checkpoint = "MBZUAI/LaMini-T5-738M"
|
| 22 |
tokenizer = AutoTokenizer.from_pretrained(checkpoint)
|
| 23 |
model = AutoModelForSeq2SeqLM.from_pretrained(checkpoint)
|
| 24 |
pipe = pipeline("text2text-generation", model=model, tokenizer=tokenizer, max_length=512)
|
| 25 |
return HuggingFacePipeline(pipeline=pipe)
|
| 26 |
|
| 27 |
+
# --- Load Embeddings ---
|
| 28 |
+
@st.cache_resource
|
| 29 |
+
def load_embeddings():
|
| 30 |
+
return HuggingFaceEmbeddings(model_name="BAAI/bge-base-en-v1.5")
|
| 31 |
+
|
| 32 |
+
# --- PDF Text Extraction ---
|
| 33 |
+
def extract_text_from_pdf(uploaded_file):
|
| 34 |
try:
|
| 35 |
+
doc = fitz.open(stream=uploaded_file.read(), filetype="pdf")
|
| 36 |
+
full_text = ""
|
| 37 |
+
for page in doc:
|
| 38 |
+
full_text += page.get_text()
|
| 39 |
+
return full_text.strip()
|
| 40 |
except Exception as e:
|
| 41 |
+
st.error(f"β Error reading PDF: {e}")
|
| 42 |
return ""
|
| 43 |
|
| 44 |
+
# --- Text Chunking ---
|
| 45 |
+
def chunk_text(full_text):
|
| 46 |
+
splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=300)
|
| 47 |
+
return splitter.create_documents([full_text])
|
| 48 |
+
|
| 49 |
+
# --- Vectorstore Setup (with in-memory temp directory) ---
|
| 50 |
+
def build_vectorstore(chunks, embeddings):
|
| 51 |
+
temp_dir = os.path.join(tempfile.gettempdir(), "chromadb-rag")
|
| 52 |
+
if os.path.exists(temp_dir):
|
| 53 |
+
shutil.rmtree(temp_dir)
|
| 54 |
+
os.makedirs(temp_dir, exist_ok=True)
|
| 55 |
+
return Chroma.from_documents(documents=chunks, embedding=embeddings, persist_directory=temp_dir)
|
| 56 |
+
|
| 57 |
+
# --- Prompt Template ---
|
| 58 |
+
def get_prompt_template():
|
| 59 |
+
return PromptTemplate(
|
| 60 |
input_variables=["context", "question"],
|
| 61 |
+
template=(
|
| 62 |
+
"You are a helpful assistant. Answer the question based only on the following context.\n\n"
|
| 63 |
+
"Context:\n{context}\n\n"
|
| 64 |
+
"Question: {question}\n\n"
|
| 65 |
+
"Answer (Be accurate and concise):"
|
| 66 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
)
|
|
|
|
| 68 |
|
| 69 |
+
# --- Answering Logic ---
|
| 70 |
+
def get_answer(question, full_text):
|
| 71 |
+
if not question or not full_text:
|
| 72 |
+
return "β οΈ Please provide both PDF and a question."
|
|
|
|
| 73 |
|
| 74 |
+
chunks = chunk_text(full_text)
|
| 75 |
+
embeddings = load_embeddings()
|
| 76 |
+
vectorstore = build_vectorstore(chunks, embeddings)
|
| 77 |
+
retriever = vectorstore.as_retriever()
|
| 78 |
|
| 79 |
+
llm = load_llm()
|
|
|
|
| 80 |
|
| 81 |
+
qa_chain = RetrievalQA.from_chain_type(
|
| 82 |
+
llm=llm,
|
| 83 |
+
retriever=retriever,
|
| 84 |
+
chain_type="stuff",
|
| 85 |
+
chain_type_kwargs={"prompt": get_prompt_template()}
|
| 86 |
+
)
|
| 87 |
|
| 88 |
+
return qa_chain.run(question)
|
|
|
|
|
|
|
| 89 |
|
| 90 |
+
# --- UI ---
|
| 91 |
with st.sidebar:
|
| 92 |
+
st.header("π Upload PDF")
|
| 93 |
+
uploaded_pdf = st.file_uploader("Upload your PDF", type=["pdf"])
|
| 94 |
|
| 95 |
+
if uploaded_pdf:
|
| 96 |
+
st.success(f"β
Uploaded: {uploaded_pdf.name}")
|
| 97 |
+
full_text = extract_text_from_pdf(uploaded_pdf)
|
|
|
|
| 98 |
|
| 99 |
if full_text:
|
| 100 |
+
with st.expander("π Preview PDF Text", expanded=False):
|
| 101 |
st.write(full_text[:3000] + ("..." if len(full_text) > 3000 else ""))
|
| 102 |
|
| 103 |
+
question = st.text_input("β Ask a question about this PDF")
|
|
|
|
| 104 |
|
| 105 |
+
if question:
|
| 106 |
+
with st.spinner("π Generating answer..."):
|
| 107 |
+
answer = get_answer(question, full_text)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 108 |
st.markdown("### π€ Answer")
|
| 109 |
st.write(answer)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
else:
|
| 111 |
+
st.error("β οΈ Could not extract any text from the PDF.")
|
| 112 |
else:
|
| 113 |
+
st.info("π₯ Upload a PDF to start.")
|
|
|
|
| 114 |
|
| 115 |
+
with st.sidebar:
|
| 116 |
+
st.markdown("---")
|
| 117 |
+
st.markdown("π‘ Try questions like:")
|
| 118 |
+
st.caption("β’ What are the key ideas?\nβ’ Summarize the document\nβ’ What is Pradeep Singh Sengar's experience?")
|