Update app.py
Browse files1 unmodified line2345656781 unmodified line101112141316141516202117181923242526272829303132202122232425373826272829303132333432 unmodified lines6768697778798070717273748283757677787980818283848511 unmodified lines9798991011001011021034 unmodified lines1081091101121111121131141 unmodified lineimport jsonimport gradio as grimport pandas as pdimport tempfilefrom typing import Listfrom tempfile import NamedTemporaryFile
from langchain_core.prompts import ChatPromptTemplatefrom langchain_community.vectorstores import FAISS1 unmodified linefrom langchain_core.output_parsers import StrOutputParserfrom langchain_community.embeddings import HuggingFaceEmbeddingsfrom langchain_community.llms import HuggingFaceHubfrom langchain_text_splitters import RecursiveCharacterTextSplitterfrom langchain_core.runnables import RunnableParallel, RunnablePassthroughfrom langchain_core.documents import Document
huggingface_token = os.environ.get("HUGGINGFACE_TOKEN")
def load_and_split_document(file: tempfile._TemporaryFileWrapper) -> List[Document]: """Loads and splits the document into chunks."""def load_and_split_document(file): """Loads and splits the document into pages.""" loader = PyPDFLoader(file.name) pages = loader.load() text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200, length_function=len, ) chunks = text_splitter.split_documents(pages) return chunks data = loader.load_and_split() return data
def get_embeddings(): return HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")
def create_database(data: List[Document], embeddings): db = FAISS.from_documents(data, embeddings)def create_or_update_database(data, embeddings): if os.path.exists("faiss_database"): db = FAISS.load_local("faiss_database", embeddings) db.add_documents(data) else: db = FAISS.from_documents(data, embeddings) db.save_local("faiss_database")
prompt = """32 unmodified lines ans = generate_chunked_response(model, formatted_prompt) return ans
def update_vectors(file): if file is None: return "Please upload a PDF file." data = load_and_split_document(file)def update_vectors(files): if not files: return "Please upload at least one PDF file." embed = get_embeddings() create_database(data, embed) return f"Vector store updated successfully. Processed {len(data)} chunks." total_chunks = 0 for file in files: data = load_and_split_document(file) create_or_update_database(data, embed) total_chunks += len(data) return f"Vector store updated successfully. Processed {total_chunks} chunks from {len(files)} files."
def ask_question(question): if not question:11 unmodified lines data = [{"page_content": doc.page_content, "metadata": json.dumps(doc.metadata)} for doc in documents] df = pd.DataFrame(data) with tempfile.NamedTemporaryFile(delete=False, suffix='.xlsx') as tmp: with NamedTemporaryFile(delete=False, suffix='.xlsx') as tmp: excel_path = tmp.name df.to_excel(excel_path, index=False) 4 unmodified lines gr.Markdown("# Chat with your PDF documents") with gr.Row(): file_input = gr.File(label="Upload your PDF document", file_types=[".pdf"]) file_input = gr.File(label="Upload your PDF documents", file_types=[".pdf"], multiple=True) update_button = gr.Button("Update Vector Store") update_output = gr.Textbox(label="Update Status")app.py+25-26