Alpaca233 commited on
Commit
31a77e6
1 Parent(s): dfb74c6

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -0
app.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+
3
+ from langchain.document_loaders import PyPDFLoader # for loading the pdf
4
+ from langchain.embeddings import OpenAIEmbeddings # for creating embeddings
5
+ from langchain.vectorstores import Chroma # for the vectorization part
6
+ from langchain.chains import ChatVectorDBChain # for chatting with the pdf
7
+ from langchain.llms import OpenAI # the LLM model we'll use (CHatGPT)
8
+
9
+
10
+ class Chat:
11
+ def __init__(self, pdf, api_input):
12
+ self.api = api_input
13
+ loader = PyPDFLoader(pdf)
14
+ pages = loader.load_and_split()
15
+
16
+ embeddings = OpenAIEmbeddings(openai_api_key=self.api)
17
+ vectordb = Chroma.from_documents(pages, embedding=embeddings, persist_directory=".")
18
+ vectordb.persist()
19
+
20
+ self.pdf_qa = ChatVectorDBChain.from_llm(OpenAI(temperature=0.9, model_name="gpt-3.5-turbo",
21
+ openai_api_key=self.api),
22
+ vectordb, return_source_documents=True)
23
+
24
+ def question(self, query):
25
+ result = self.pdf_qa({"question": "请使用中文回答" + query, "chat_history": ""})
26
+ print("Answer:")
27
+ print(result["answer"])
28
+
29
+ return result["answer"]
30
+
31
+
32
+ def analyse(pdf_file, api_input):
33
+ session = Chat(pdf_file.name, api_input)
34
+ return session, "文章分析完成"
35
+
36
+
37
+ def ask_question(data, question):
38
+ if data == "":
39
+ return "Please upload PDF file first!"
40
+ return data.question(question)
41
+
42
+
43
+ with gr.Blocks() as demo:
44
+ gr.Markdown(
45
+ """
46
+ # ChatPDF based on Langchain
47
+ """)
48
+ data = gr.State()
49
+ with gr.Tab("Upload PDF File"):
50
+ pdf_input = gr.File(label="PDF File")
51
+ api_input = gr.Textbox(label="OpenAI API Key")
52
+ result = gr.Textbox()
53
+ upload_button = gr.Button("Start Analyse")
54
+ question_input = gr.Textbox(label="Your Question", placeholder="Authors of this paper?")
55
+ answer = gr.Textbox(label="Answer")
56
+ ask_button = gr.Button("Ask")
57
+
58
+ upload_button.click(fn=analyse, inputs=[pdf_input, api_input], outputs=[data, result])
59
+ ask_button.click(ask_question, inputs=[data, question_input], outputs=answer)
60
+
61
+ if __name__ == "__main__":
62
+ demo.title = "ChatPDF Based on Langchain"
63
+ demo.launch()