File size: 2,237 Bytes
203e2cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4771719
203e2cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
51
52
53
54
55
56
57
58
59
60
61
62
import gradio as gr
import os 
from langchain.chains import RetrievalQA
from langchain.llms import OpenAI
from langchain.document_loaders import PyPDFLoader
from langchain.text_splitter import CharacterTextSplitter
from langchain.embeddings import OpenAIEmbeddings
from langchain.vectorstores import Chroma

def qa_system(pdf_file, openai_key, prompt, chain_type, k):
    os.environ["OPENAI_API_KEY"] = openai_key
    
    # load document
    loader = PyPDFLoader(pdf_file.name)
    documents = loader.load()
    
    # split the documents into chunks
    text_splitter = CharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
    texts = text_splitter.split_documents(documents)
    
    # select which embeddings we want to use
    embeddings = OpenAIEmbeddings()
    
    # create the vectorestore to use as the index
    db = Chroma.from_documents(texts, embeddings)
    
    # expose this index in a retriever interface
    retriever = db.as_retriever(search_type="similarity", search_kwargs={"k": k})
    
    # create a chain to answer questions 
    qa = RetrievalQA.from_chain_type(
        llm=OpenAI(), chain_type=chain_type, retriever=retriever, return_source_documents=True)
    
    # get the result
    result = qa({"query": prompt})
    return result['result'], [doc.page_content for doc in result["source_documents"]]

# define the Gradio interface
input_file = gr.inputs.File(label="PDF File")
openai_key = gr.inputs.Textbox(label="OpenAI API Key", type="password")
prompt = gr.inputs.Textbox(label="Question Prompt")
chain_type = gr.inputs.Radio(['stuff', 'map_reduce', "refine", "map_rerank"], label="Chain Type")
k = gr.inputs.Slider(minimum=1, maximum=5, default=1, label="Number of Relevant Chunks")

output_text = gr.outputs.Textbox(label="Answer")
output_docs = gr.outputs.Textbox(label="Relevant Source Text")

gr.Interface(qa_system, inputs=[input_file, openai_key, prompt, chain_type, k], outputs=[output_text, output_docs], 
             title="Question Answering with PDF File and OpenAI", 
             description="Upload a PDF file, enter your OpenAI API key, type a question prompt, select a chain type, and choose the number of relevant chunks to use for the answer.").launch(debug = True)