Spaces:
Sleeping
Sleeping
import os | |
from langchain import PromptTemplate | |
from langchain.chains.question_answering import load_qa_chain | |
from langchain.document_loaders import PyPDFLoader | |
from langchain_google_genai import ChatGoogleGenerativeAI | |
import google.generativeai as genai | |
import gradio as gr | |
import os | |
import gradio as gr | |
from langchain import PromptTemplate | |
from langchain.chains.question_answering import load_qa_chain | |
from langchain.document_loaders import PyPDFLoader | |
from langchain_google_genai import ChatGoogleGenerativeAI | |
import google.generativeai as genai | |
from dotenv import load_dotenv | |
# Load environment variables from .env file | |
load_dotenv() | |
# Function for initialisation | |
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) | |
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." | |
def chatbot(file): | |
file_path = file.name | |
question_input = file.read() | |
return initialize(file_path, question_input) | |
# Create Gradio interface | |
inputs = gr.inputs.File(label="Upload PDF") | |
outputs = gr.outputs.Textbox(label="Answer - GeminiPro") | |
gr.Interface(fn=chatbot, inputs=inputs, outputs=outputs, title="GeminiPro Q&A Bot", description="Ask questions about the uploaded PDF document.").launch() | |