File size: 2,262 Bytes
cc82b37
020ff2f
701dcc2
801cf0e
 
 
140729c
 
01121a5
140729c
8f4ce98
701dcc2
140729c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a19f3c
 
140729c
 
 
 
1a19f3c
140729c
8d84dff
 
 
140729c
701dcc2
 
140729c
 
 
 
01121a5
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
import os
import gradio as gr
import asyncio
from langchain_core.prompts import PromptTemplate
from langchain_community.output_parsers.rail_parser import GuardrailsOutputParser
from langchain_community.document_loaders import PyPDFLoader
from langchain_google_genai import ChatGoogleGenerativeAI
import google.generativeai as genai
from langchain.chains.question_answering import load_qa_chain  # Import load_qa_chain


async def initialize(file_path, question):
    genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
    model = genai.GenerativeModel('gemini-pro')
    model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
    prompt_template = """Answer the question as precise as possible using the provided context. If the answer is
                          not contained in the context, say "answer not available in context" \n\n
                          Context: \n {context}?\n
                          Question: \n {question} \n
                          Answer:
                        """
    prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
    if os.path.exists(file_path):
        pdf_loader = PyPDFLoader(file_path)
        pages = pdf_loader.load_and_split()
        context = "\n".join(str(page.page_content) for page in pages[:30])
        stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
        # Refactor the below line to make sure it returns an awaitable object
        stuff_answer = stuff_chain({"input_documents": pages, "question": question, "context": context}, return_only_outputs=True)
        return stuff_answer['output_text']
    else:
        return "Error: Unable to process the document. Please ensure the PDF file is valid."


# Define Gradio Interface
input_file = gr.File(label="Upload PDF File")
input_question = gr.Textbox(label="Ask about the document")
output_text = gr.Textbox(label="Answer - GeminiPro")

async def pdf_qa(file, question):
    answer = await initialize(file.name, question)
    return answer

# Create Gradio Interface
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()