xnetba/PDFapp
0
1import gradio as gr2from langchain.document_loaders import OnlinePDFLoader3from langchain.text_splitter import CharacterTextSplitter4from langchain.llms import HuggingFaceHub5from langchain.embeddings import HuggingFaceHubEmbeddings6from langchain.vectorstores import Chroma7from langchain.chains import RetrievalQA8 9def loading_pdf():10 return "Loading..."11 12def pdf_changes(pdf_doc, repo_id):13 14 loader = OnlinePDFLoader(pdf_doc.name)15 documents = loader.load()16 text_splitter = CharacterTextSplitter(chunk_size=300, chunk_overlap=0)17 texts = text_splitter.split_documents(documents)18 embeddings = HuggingFaceHubEmbeddings()19 db = Chroma.from_documents(texts, embeddings)20 retriever = db.as_retriever()21 llm = HuggingFaceHub(repo_id=repo_id, model_kwargs={"temperature":0.1, "max_new_tokens":250})22 global qa 23 qa = RetrievalQA.from_chain_type(llm=llm, chain_type="stuff", retriever=retriever, return_source_documents=True)24 return "Ready"25 26def add_text(history, text):27 history = history + [(text, None)]28 return history, ""29 30def bot(history):31 response = infer(history[-1][0])32 history[-1][1] = response['result']33 return history34 35def infer(question):36 37 query = question38 result = qa({"query": query})39 return result40 41css="""42#col-container {max-width: 700px; margin-left: auto; margin-right: auto;}43"""44 45title = """46<div style="text-align: center;max-width: 700px;">47 <h1>Chat with PDF</h1>48 <p style="text-align: center;">Upload a .PDF from your computer, click the "Load PDF to LangChain" button, <br />49 when everything is ready, you can start asking questions about the pdf ;)</p>50 <a style="display:inline-block; margin-left: 1em" href="https://huggingface.co/spaces/fffiloni/langchain-chat-with-pdf?duplicate=true"><img src="https://img.shields.io/badge/-Duplicate%20Space%20to%20skip%20the%20queue-blue?labelColor=white&style=flat&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAAAXNSR0IArs4c6QAAAP5JREFUOE+lk7FqAkEURY+ltunEgFXS2sZGIbXfEPdLlnxJyDdYB62sbbUKpLbVNhyYFzbrrA74YJlh9r079973psed0cvUD4A+4HoCjsA85X0Dfn/RBLBgBDxnQPfAEJgBY+A9gALA4tcbamSzS4xq4FOQAJgCDwV2CPKV8tZAJcAjMMkUe1vX+U+SMhfAJEHasQIWmXNN3abzDwHUrgcRGmYcgKe0bxrblHEB4E/pndMazNpSZGcsZdBlYJcEL9Afo75molJyM2FxmPgmgPqlWNLGfwZGG6UiyEvLzHYDmoPkDDiNm9JR9uboiONcBXrpY1qmgs21x1QwyZcpvxt9NS09PlsPAAAAAElFTkSuQmCC&logoWidth=14" alt="Duplicate Space"></a>51</div>52"""53 54with gr.Blocks(css=css) as demo:55 with gr.Column(elem_id="col-container"):56 gr.HTML(title)57 58 with gr.Column():59 pdf_doc = gr.File(label="Load a pdf", file_types=['.pdf'], type="file")60 repo_id = gr.Dropdown(label="LLM", choices=["google/flan-ul2", "OpenAssistant/oasst-sft-1-pythia-12b", "bigscience/bloomz"], value="google/flan-ul2")61 with gr.Row():62 langchain_status = gr.Textbox(label="Status", placeholder="", interactive=False)63 load_pdf = gr.Button("Load pdf to langchain")64 65 chatbot = gr.Chatbot([], elem_id="chatbot").style(height=350)66 question = gr.Textbox(label="Question", placeholder="Type your question and hit Enter ")67 submit_btn = gr.Button("Send message")68 #load_pdf.click(loading_pdf, None, langchain_status, queue=False) 69 repo_id.change(pdf_changes, inputs=[pdf_doc, repo_id], outputs=[langchain_status], queue=False)70 load_pdf.click(pdf_changes, inputs=[pdf_doc, repo_id], outputs=[langchain_status], queue=False)71 question.submit(add_text, [chatbot, question], [chatbot, question]).then(72 bot, chatbot, chatbot73 )74 submit_btn.click(add_text, [chatbot, question], [chatbot, question]).then(75 bot, chatbot, chatbot76 )77 78demo.launch()79 