chukbert commited on
Commit
40c201c
1 Parent(s): 4be3b14

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +67 -0
app.py ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ from langchain.document_loaders import PyPDFLoader
4
+ from langchain.llms import OpenAI
5
+ from langchain.chains import load_qa_chain
6
+ from langchain.chains.combine_documents import create_stuff_documents_chain
7
+ from langchain_core.prompts import ChatPromptTemplate
8
+ from langchain.text_splitter import RecursiveCharacterTextSplitter
9
+
10
+ # Setup OpenAI API key (replace with your OpenAI API key)
11
+ openai.api_key = os.getenv("OPENAI_API_KEY")
12
+ # Initialize GPT-4o-mini model
13
+ llm = OpenAI(model_name="gpt-4o-mini")
14
+
15
+ # Function to load PDF document
16
+ def load_pdf(file):
17
+ loader = PyPDFLoader(file.name)
18
+ documents = loader.load()
19
+ return documents
20
+
21
+ # Summarization using the "stuff" method
22
+ def summarize_pdf(file):
23
+ docs = load_pdf(file)
24
+
25
+ # Define a prompt for summarization
26
+ prompt = ChatPromptTemplate.from_messages([("system", "Write a concise summary of the following:\n\n{context}")])
27
+
28
+ # Create summarization chain
29
+ chain = create_stuff_documents_chain(llm, prompt)
30
+ summary = chain.invoke({"context": docs})
31
+ return summary['result']
32
+
33
+ # Question Answering on PDF
34
+ def qa_on_pdf(file, question):
35
+ docs = load_pdf(file)
36
+
37
+ # Create QA chain
38
+ qa_chain = load_qa_chain(llm)
39
+ response = qa_chain.run({"input_documents": docs, "question": question})
40
+ return response
41
+
42
+ # Gradio interface
43
+ def create_interface():
44
+ # Define the interface components
45
+ with gr.Blocks() as interface:
46
+ gr.Markdown("# Research Paper Summarization and QA")
47
+
48
+ with gr.Row():
49
+ with gr.Column():
50
+ pdf_file = gr.File(label="Upload Research Paper PDF")
51
+ summarize_btn = gr.Button("Summarize PDF")
52
+ summary_output = gr.Textbox(label="Summary", lines=10)
53
+
54
+ summarize_btn.click(summarize_pdf, inputs=[pdf_file], outputs=[summary_output])
55
+
56
+ with gr.Column():
57
+ qa_question = gr.Textbox(label="Ask a Question about the PDF", placeholder="Type your question here...")
58
+ qa_btn = gr.Button("Submit Question")
59
+ qa_output = gr.Textbox(label="Answer", lines=10)
60
+
61
+ qa_btn.click(qa_on_pdf, inputs=[pdf_file, qa_question], outputs=[qa_output])
62
+
63
+ return interface
64
+
65
+ # Launch Gradio app
66
+ interface = create_interface()
67
+ interface.launch()