File size: 1,675 Bytes
7e93e39
bac8651
7e93e39
cbf8726
7e93e39
 
 
cbf8726
7e93e39
cbf8726
 
7e93e39
cbf8726
 
7e93e39
cbf8726
 
7e93e39
cbf8726
7e93e39
 
 
 
cbf8726
 
7e93e39
cbf8726
7e93e39
 
 
cbf8726
 
 
 
 
 
 
7e93e39
cbf8726
 
 
 
 
 
 
7e93e39
cbf8726
7e93e39
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import gradio as gr
from langchain_community.document_loaders.pdf import PyPDFLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain_community.embeddings import HuggingFaceEmbeddings
from langchain.vectorstores import FAISS
from langchain.chains import RetrievalQA
from transformers import pipeline
from langchain.llms import HuggingFacePipeline

def process_pdf(pdf):
    loader = PyPDFLoader(pdf.name)
    pages = loader.load()
    text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=200)
    docs = text_splitter.split_documents(pages)

    embeddings = HuggingFaceEmbeddings(model_name="all-MiniLM-L6-v2")
    db = FAISS.from_documents(docs, embeddings)

    qa_pipeline = pipeline("text-generation", model="tiiuae/falcon-rw-1b", max_new_tokens=512)
    llm = HuggingFacePipeline(pipeline=qa_pipeline)

    qa = RetrievalQA.from_chain_type(llm=llm, retriever=db.as_retriever())

    def ask_question(q):
        return qa.run(q)

    return gr.Interface(fn=ask_question, inputs="text", outputs="text", title="🧠 PDF Chatbot")

with gr.Blocks() as demo:
    with gr.Row():
        pdf_input = gr.File(label="Upload your PDF")
    output_interface = gr.State()

    def load_pdf(file):
        output_interface.value = process_pdf(file)
        return "PDF loaded. Ask away below 👇"

    with gr.Row():
        load_btn = gr.Button("Load PDF")
        load_msg = gr.Textbox(interactive=False)

    load_btn.click(load_pdf, inputs=[pdf_input], outputs=[load_msg])

    chatbot = gr.Interface(fn=lambda x: output_interface.value(x),
                           inputs="text", outputs="text")

    chatbot.render()

demo.launch()