Update app.py
Browse files1 unmodified line234567891 unmodified line1112131415161718192021222324252627282930313233343536373839404132 unmodified lines7475767778798081828384858611 unmodified lines98991001011021031044 unmodified lines1091101111121131141151 unmodified lineimport jsonimport gradio as grimport pandas as pdimport tempfilefrom typing import Listfrom 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 Documenthuggingface_token = os.environ.get("HUGGINGFACE_TOKEN")def load_and_split_document(file: tempfile._TemporaryFileWrapper) -> List[Document]:"""Loads and splits the document into chunks."""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 chunksdef 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)db.save_local("faiss_database")prompt = """32 unmodified linesans = generate_chunked_response(model, formatted_prompt)return ansdef update_vectors(file):if file is None:return "Please upload a PDF file."data = load_and_split_document(file)embed = get_embeddings()create_database(data, embed)return f"Vector store updated successfully. Processed {len(data)} chunks."def ask_question(question):if not question:11 unmodified linesdata = [{"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:excel_path = tmp.namedf.to_excel(excel_path, index=False)4 unmodified linesgr.Markdown("# Chat with your PDF documents")with gr.Row():file_input = gr.File(label="Upload your PDF document", file_types=[".pdf"])update_button = gr.Button("Update Vector Store")update_output = gr.Textbox(label="Update Status")1 unmodified line23456781 unmodified line1011121314151617181920212223242526272829303132333432 unmodified lines6768697071727374757677787980818283848511 unmodified lines9798991001011021034 unmodified lines1081091101111121131141 unmodified lineimport jsonimport gradio as grimport pandas as pdfrom tempfile import NamedTemporaryFilefrom 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_core.runnables import RunnableParallel, RunnablePassthroughhuggingface_token = os.environ.get("HUGGINGFACE_TOKEN")def load_and_split_document(file):"""Loads and splits the document into pages."""loader = PyPDFLoader(file.name)data = loader.load_and_split()return datadef get_embeddings():return HuggingFaceEmbeddings(model_name="sentence-transformers/all-mpnet-base-v2")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 linesans = generate_chunked_response(model, formatted_prompt)return ansdef update_vectors(files):if not files:return "Please upload at least one PDF file."embed = get_embeddings()total_chunks = 0for 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 linesdata = [{"page_content": doc.page_content, "metadata": json.dumps(doc.metadata)} for doc in documents]df = pd.DataFrame(data)with NamedTemporaryFile(delete=False, suffix='.xlsx') as tmp:excel_path = tmp.namedf.to_excel(excel_path, index=False)4 unmodified linesgr.Markdown("# Chat with your PDF documents")with gr.Row():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