saritha commited on
Commit
cc82b37
·
verified ·
1 Parent(s): 5efe6a9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +55 -0
app.py CHANGED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from langchain import PromptTemplate
3
+ from langchain.chains.question_answering import load_qa_chain
4
+ from langchain.document_loaders import PyPDFLoader
5
+ from langchain_google_genai import ChatGoogleGenerativeAI
6
+ import google.generativeai as genai
7
+ import gradio as gr
8
+
9
+ import os
10
+ import gradio as gr
11
+ from langchain import PromptTemplate
12
+ from langchain.chains.question_answering import load_qa_chain
13
+ from langchain.document_loaders import PyPDFLoader
14
+ from langchain_google_genai import ChatGoogleGenerativeAI
15
+ import google.generativeai as genai
16
+ from dotenv import load_dotenv
17
+
18
+ # Load environment variables from .env file
19
+ load_dotenv()
20
+
21
+ # Function for initialisation
22
+ def initialize(file_path, question):
23
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
24
+ model = genai.GenerativeModel('gemini-pro')
25
+ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
26
+ prompt_template = """Answer the question as precise as possible using the provided context. If the answer is
27
+ not contained in the context, say "answer not available in context" \n\n
28
+ Context: \n {context}?\n
29
+ Question: \n {question} \n
30
+ Answer:
31
+ """
32
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
33
+ if os.path.exists(file_path):
34
+ pdf_loader = PyPDFLoader(file_path)
35
+ pages = pdf_loader.load_and_split()
36
+ context = "\n".join(str(page.page_content) for page in pages[:30])
37
+ stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
38
+ stuff_answer = stuff_chain({"input_documents": pages, "question": question, "context": context}, return_only_outputs=True)
39
+ return stuff_answer['output_text']
40
+ else:
41
+ return "Error: Unable to process the document. Please ensure the PDF file is valid."
42
+
43
+ def chatbot(file):
44
+ file_path = file.name
45
+ question_input = file.read()
46
+ return initialize(file_path, question_input)
47
+
48
+ # Create Gradio interface
49
+ inputs = gr.inputs.File(label="Upload PDF")
50
+ outputs = gr.outputs.Textbox(label="Answer - GeminiPro")
51
+
52
+ gr.Interface(fn=chatbot, inputs=inputs, outputs=outputs, title="GeminiPro Q&A Bot", description="Ask questions about the uploaded PDF document.").launch()
53
+
54
+
55
+