# Import necessary libraries import gradio as gr from langchain.document_loaders import OnlinePDFLoader from langchain.text_splitter import CharacterTextSplitter from langchain.llms import HuggingFaceHub from langchain.embeddings import HuggingFaceHubEmbeddings from langchain.vectorstores import Chroma from langchain.chains import RetrievalQA # Define a function to display "Loading..." when loading a PDF def loading_pdf(): return "Loading..." # Define a function to process PDF changes def pdf_changes(pdf_doc, repo_id): # Initialize the OnlinePDFLoader to load the PDF document loader = OnlinePDFLoader(pdf_doc.name) documents = loader.load() # Split the loaded documents into chunks using CharacterTextSplitter text_splitter = CharacterTextSplitter(chunk_size=400, chunk_overlap=50) texts = text_splitter.split_documents(documents) # Initialize HuggingFaceHubEmbeddings for embeddings embeddings = HuggingFaceHubEmbeddings() # Create a Chroma vector store from the text chunks and embeddings db = Chroma.from_documents(texts, embeddings) # Convert the vector store to a retriever retriever = db.as_retriever() # Initialize an HuggingFaceHub language model (LLM) llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={"temperature": 0.25, "max_new_tokens": 1000}) # Create a RetrievalQA chain with the LLM, retriever, and return_source_documents option global qa qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=True) return "Ready" # Define a function to add text to a history def add_text(history, text): history = history + [(text, None)] return history, "" # Define a bot function to generate responses def bot(history): response = infer(history[-1][0]) history[-1][1] = response['result'] return history # Define an inference function to query the LLM def infer(query): result = qa({"query": query}) return result # Define custom CSS styles css = """ #col-container {max-width: 700px; margin-left: auto; margin-right: auto;} """ # Define a title HTML for the interface title = """
Upload a .PDF from your computer, click the "Load PDF to LangChain" button,
when everything is ready, you can start asking questions about the PDF ;)