YU-XI commited on
Commit
f43f191
·
verified ·
1 Parent(s): fa72f28

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +47 -0
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import asyncio
4
+ from langchain_core.prompts import PromptTemplate
5
+ from langchain_community.output_parsers.rail_parser import GuardrailsOutputParser
6
+ from langchain_community.document_loaders import PyPDFLoader
7
+ from langchain_google_genai import ChatGoogleGenerativeAI
8
+ import google.generativeai as genai
9
+ from langchain.chains.question_answering import load_qa_chain # Import load_qa_chain
10
+
11
+
12
+ async def initialize(file_path, question):
13
+ genai.configure(api_key=os.getenv("AIzaSyBcGzp4xqhpM3K3g7J_2xAr55Sy_rE0n1g"))
14
+ model = genai.GenerativeModel('gemini-pro')
15
+ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
16
+ prompt_template = """Answer the question as precise as possible using the provided context. If the answer is
17
+ not contained in the context, say "answer not available in context" \n\n
18
+ Context: \n {context}?\n
19
+ Question: \n {question} \n
20
+ Answer:
21
+ """
22
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
23
+ if os.path.exists(file_path):
24
+ pdf_loader = PyPDFLoader(file_path)
25
+ pages = pdf_loader.load_and_split()
26
+ context = "\n".join(str(page.page_content) for page in pages[:30])
27
+ stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
28
+ # Refactor the below line to make sure it returns an awaitable object
29
+ stuff_answer = stuff_chain({"input_documents": pages, "question": question, "context": context}, return_only_outputs=True)
30
+ return stuff_answer['output_text']
31
+ else:
32
+ return "Error: Unable to process the document. Please ensure the PDF file is valid."
33
+
34
+
35
+ # Define Gradio Interface
36
+ input_file = gr.File(label="Upload PDF File")
37
+ input_question = gr.Textbox(label="Ask about the document")
38
+ output_text = gr.Textbox(label="Answer - GeminiPro")
39
+
40
+ async def pdf_qa(file, question):
41
+ answer = await initialize(file.name, question)
42
+ return answer
43
+
44
+ # Create Gradio Interface
45
+ gr.Interface(fn=pdf_qa, inputs=[input_file, input_question], outputs=output_text, title="PDF Question Answering System", description="Upload a PDF file and ask questions about the content.").launch()
46
+
47
+