saritha commited on
Commit
ac04873
·
verified ·
1 Parent(s): 882a79c

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +60 -0
app.py ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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("GOOGLE_API_KEY"))
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(f"Page {i+1}: {page.page_content}" for i, page in enumerate(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 = await stuff_chain.arun({"input_documents": pages, "question": question, "context": context})
30
+
31
+ # Extract the page number where the context was found
32
+ sources = []
33
+ for i, page in enumerate(pages):
34
+ if question.lower() in page.page_content.lower():
35
+ sources.append(f"Page {i+1}")
36
+
37
+ if sources:
38
+ source_str = f" (Source: {', '.join(sources)})"
39
+ else:
40
+ source_str = " (Source: Not found in specific page)"
41
+
42
+ # Add the clickable link to the source
43
+ file_name = os.path.basename(file_path)
44
+ source_link = f"[{file_name}](file://{os.path.abspath(file_path)})"
45
+ return f"{stuff_answer['output_text']} {source_str} - [Document: {source_link}]"
46
+ else:
47
+ return "Error: Unable to process the document. Please ensure the PDF file is valid."
48
+
49
+
50
+ # Define Gradio Interface
51
+ input_file = gr.File(label="Upload PDF File")
52
+ input_question = gr.Textbox(label="Ask about the document")
53
+ output_text = gr.Textbox(label="Answer - GeminiPro")
54
+
55
+ async def pdf_qa(file, question):
56
+ answer = await initialize(file.name, question)
57
+ return answer
58
+
59
+ # Create Gradio Interface
60
+ 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()