Spaces:
Sleeping
Sleeping
Update app.py
Browse files421 unmodified lines42242342442542642742842943043143243343443543643743843944044144220 unmodified lines46346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555611 unmodified lines5685695705715725735745755765775785795805815826 unmodified lines5895905915925935945955965975985996001 unmodified line6026036046056066076089 unmodified lines6186196206216226236242 unmodified lines627628629630631632633421 unmodified linesimport streamlit as stimport fitz # PyMuPDFimport loggingimport mathfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipelinefrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_community.vectorstores import Chromafrom langchain_community.embeddings import SentenceTransformerEmbeddingsfrom langchain_community.llms import HuggingFacePipelinefrom langchain.chains import RetrievalQAfrom langchain.schema import Documentfrom sentence_transformers import SentenceTransformerfrom langchain_community.embeddings import HuggingFaceEmbeddings# --- Configuration ---st.set_page_config(page_title="π RAG PDF Chatbot", layout="wide")st.title("π RAG-based PDF Chatbot")persist_directory = "db"device = "cpu"# --- Logging ---20 unmodified lineslogging.error(f"Failed to extract text: {e}")return ""# --- Split Text into Chunks ---def split_text_into_chunks(text):splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=50)return splitter.create_documents([text])import osimport shutilfrom sentence_transformers import SentenceTransformerfrom langchain.embeddings import HuggingFaceEmbeddingsfrom langchain.vectorstores import Chroma# Setup a writable directory for Chromachroma_dir = "/home/user/app/chroma_db" # Change this to an absolute writable directoryif os.path.exists(chroma_dir):shutil.rmtree(chroma_dir) # Clear any old dataos.makedirs(chroma_dir, exist_ok=True)# Initialize the model and embeddingsmodel = SentenceTransformer("all-MiniLM-L6-v2", device='cpu')embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")# Create the Chroma databasetry:db = Chroma.from_documents(splits, embeddings, persist_directory=chroma_dir)db.persist()print(f"Vectorstore created successfully at {chroma_dir}")except Exception as e:print(f"Error creating vectorstore: {e}")# --- Setup QA Chain ---def setup_qa(db):retriever = db.as_retriever()llm = load_model()return RetrievalQA.from_chain_type(llm=llm, retriever=retriever, return_source_documents=True)# --- Process Answer ---# def process_answer(question, full_text):# # STEP 1: Chunk the PDF text# text_splitter = RecursiveCharacterTextSplitter(chunk_size=500, chunk_overlap=100)# docs = text_splitter.create_documents([full_text])# # STEP 2: Create embeddings# embeddings = SentenceTransformerEmbeddings(model_name="all-MiniLM-L6-v2")# db = Chroma.from_documents(docs, embeddings)# # STEP 3: Retrieve relevant chunks using the question# retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": 5})# relevant_docs = retriever.get_relevant_documents(question)# # STEP 4: Format the context# context = "\n\n".join([doc.page_content for doc in relevant_docs])# # STEP 5: Prompting# prompt_template = """# You are a helpful assistant that answers questions based on the context below.# Context:# {context}# Question: {question}# Answer:# """.strip()# prompt = prompt_template.format(context=context, question=question)# # STEP 6: Load the model and generate response# llm = HuggingFacePipeline.from_model_id(# model_id="MBZUAI/LaMini-T5-738M",# task="text2text-generation",# model_kwargs={"temperature": 0.3, "max_length": 256},# )# return llm.invoke(prompt)import tempfileimport osdef process_answer(question, full_text):from langchain_community.document_loaders import TextLoaderfrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain.vectorstores import Chromafrom langchain_community.embeddings import SentenceTransformerEmbeddingsfrom langchain.chains import RetrievalQAfrom langchain import HuggingFacePipelinefrom transformers import pipeline# Save the full_text to a temporary filewith open("temp_text.txt", "w") as f:f.write(full_text)11 unmodified lines# Create a temporary directory for ChromaDBchroma_dir = os.path.join(tempfile.gettempdir(), "chroma_db")if os.path.exists(chroma_dir):import shutilshutil.rmtree(chroma_dir)db = Chroma.from_documents(splits, embeddings, persist_directory=chroma_dir)retriever = db.as_retriever()# Set up the modelpipe = pipeline("text2text-generation", model="MBZUAI/LaMini-T5-738M", max_length=512)llm = HuggingFacePipeline(pipeline=pipe)# RAG-style retrieval QAqa_chain = RetrievalQA.from_chain_type(llm=llm, retriever=retriever)6 unmodified lineselse:return qa_chain.run(question)# --- UI Layout ---with st.sidebar:st.header("π Upload PDF")uploaded_file = st.file_uploader("Choose a PDF", type=["pdf"])# --- Main Interface ---if uploaded_file:1 unmodified linefull_text = read_pdf(uploaded_file)if full_text:st.subheader("π PDF Preview")with st.expander("View Extracted Text"):st.write(full_text[:3000] + ("..." if len(full_text) > 3000 else ""))9 unmodified lineswith st.sidebar:st.markdown("---")st.markdown("**π‘ Suggestions:**")st.caption("Try: \"Summarize this document\" or \"What is the key idea?\"")with st.expander("π‘ Suggestions", expanded=True):st.markdown("""- "Summarize this document"2 unmodified lines- "Explain this document in short"""")else:st.error("β οΈ No text could be extracted from the PDF. Try another file.")else:421 unmodified lines42242342442542642742842943043143243343443543643743843944020 unmodified lines46146246346446546646746811 unmodified lines4804814824834844854864874884894904914926 unmodified lines4995005015025035045055065075081 unmodified line5105115125135145155169 unmodified lines5265275285295305315322 unmodified lines535536537538539540421 unmodified linesimport streamlit as stimport fitz # PyMuPDFimport loggingimport tempfileimport shutilfrom transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipelinefrom langchain.text_splitter import RecursiveCharacterTextSplitterfrom langchain_community.vectorstores import Chromafrom langchain_community.embeddings import SentenceTransformerEmbeddingsfrom langchain_community.llms import HuggingFacePipelinefrom langchain.chains import RetrievalQAfrom langchain_community.document_loaders import TextLoader# --- Configuration ---st.set_page_config(page_title="π RAG PDF Chatbot", layout="wide")st.title("π RAG-based PDF Chatbot")device = "cpu"# --- Logging ---20 unmodified lineslogging.error(f"Failed to extract text: {e}")return ""# --- Process Answer ---def process_answer(question, full_text):# Save the full_text to a temporary filewith open("temp_text.txt", "w") as f:f.write(full_text)11 unmodified lines# Create a temporary directory for ChromaDBchroma_dir = os.path.join(tempfile.gettempdir(), "chroma_db")if os.path.exists(chroma_dir):shutil.rmtree(chroma_dir)db = Chroma.from_documents(splits, embeddings, persist_directory=chroma_dir)retriever = db.as_retriever()# Set up the modelllm = load_model()# RAG-style retrieval QAqa_chain = RetrievalQA.from_chain_type(llm=llm, retriever=retriever)6 unmodified lineselse:return qa_chain.run(question)# --- UI Layout ---with st.sidebar:st.header("π Upload PDF")uploaded_file = st.file_uploader("Choose a PDF", type=["pdf"])# --- Main Interface ---if uploaded_file:1 unmodified linefull_text = read_pdf(uploaded_file)if full_text:st.subheader("π PDF Preview")with st.expander("View Extracted Text"):st.write(full_text[:3000] + ("..." if len(full_text) > 3000 else ""))9 unmodified lineswith st.sidebar:st.markdown("---")st.markdown("**π‘ Suggestions:**")st.caption("Try: \"Summarize this document\" or \"What is the key idea?\")with st.expander("π‘ Suggestions", expanded=True):st.markdown("""- "Summarize this document"2 unmodified lines- "Explain this document in short"""")else:st.error("β οΈ No text could be extracted from the PDF. Try another file.")else:
app.py+6-99