saritha commited on
Commit
140729c
·
verified ·
1 Parent(s): 88f41cb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -86
app.py CHANGED
@@ -1,89 +1,46 @@
1
  import os
2
- from langchain_core.prompts import PromptTemplate
3
- from langchain_community.output_parsers.rail_parser import GuardrailsOutputParser
4
- from langchain_community.document_loaders import PyPDFLoader
5
- import google.generativeai as genai
6
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
- # Function for initialization
9
- def initialize(pdf_file, question):
10
- try:
11
- # Access the uploaded file information from Gradio
12
- file_info = pdf_file
13
-
14
- # Check if a file was uploaded
15
- if file_info is not None:
16
- # Construct potential file path based on temporary directory and filename
17
- file_path = os.path.join("/tmp", file_info.name) # Adjust temporary directory if needed
18
- if os.path.exists(file_path):
19
- # Process the PDF
20
- pdf_loader = PyPDFLoader(file_path)
21
- pages = pdf_loader.load_and_split()
22
- processed_context = "\n".join(str(page.page_content) for page in pages[:30]) # Limit to first 30 pages
23
-
24
- # Configure Google Generative AI (replace with your API key)
25
- genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
26
-
27
- # Prompt template for formatting context and question
28
- 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"
29
-
30
- Context:
31
- {context}
32
-
33
- Question:
34
- {question}
35
-
36
- Answer:
37
- """
38
-
39
- prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
40
-
41
- # Load the GeminiPro model
42
- model = genai.GenerativeModel('gemini-pro')
43
-
44
- # Option 1: Using GeminiPro's Text Generation (if applicable)
45
-
46
- # Check if the model has a 'generate' method (or similar) - adjust based on actual method
47
- if hasattr(model, 'generate'):
48
- # Process context and question (already done)
49
-
50
- # Generate answer using GeminiPro's generate method
51
- generated_answer = model.generate(prompt=prompt) # Replace with the appropriate method
52
-
53
- # Extract the answer (parse the output from 'generate')
54
- # ... (implementation depends on the model's output format)
55
-
56
- return generated_answer
57
-
58
- # Option 2: Alternative LLM Integration (if GeminiPro methods not suitable)
59
-
60
- # Replace this section with code using an alternative library/framework
61
- # for question answering (e.g., transformers, haystack)
62
- # Ensure the code integrates with your chosen LLM and handles context processing,
63
- # question answering, and answer extraction.
64
-
65
- # Example placeholder (replace with your actual implementation):
66
- # return "Alternative LLM integration not yet implemented."
67
-
68
- else:
69
- return "Error: The uploaded file could not be found."
70
- else:
71
- return "Error: No PDF file was uploaded."
72
-
73
- except Exception as e:
74
- return f"An error occurred: {e}" # Generic error handling
75
-
76
- # Create a Gradio interface
77
- interface = gr.Interface(
78
- fn=initialize,
79
- inputs=[
80
- gr.File(label="Upload PDF"), # No need for 'type' argument
81
- gr.Textbox(label="Question")
82
- ],
83
- outputs="text",
84
- title="GeminiPro Q&A Bot",
85
- description="Ask questions about the uploaded PDF document.",
86
- )
87
-
88
- # Launch the interface
89
- interface.launch()
 
1
  import os
 
 
 
 
2
  import gradio as gr
3
+ from langchain import PromptTemplate
4
+ from langchain.chains.question_answering import load_qa_chain
5
+ from langchain.document_loaders import PyPDFLoader
6
+ from langchain_google_genai import ChatGoogleGenerativeAI
7
+ import google.generativeai as genai
8
+ from dotenv import load_dotenv
9
+
10
+ # Load environment variables from .env file
11
+ load_dotenv()
12
+
13
+ # Fungsi untuk inisialisasi
14
+ def initialize(file_path, question):
15
+ genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
16
+ model = genai.GenerativeModel('gemini-pro')
17
+ model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
18
+ prompt_template = """Answer the question as precise as possible using the provided context. If the answer is
19
+ not contained in the context, say "answer not available in context" \n\n
20
+ Context: \n {context}?\n
21
+ Question: \n {question} \n
22
+ Answer:
23
+ """
24
+ prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
25
+ if os.path.exists(file_path):
26
+ pdf_loader = PyPDFLoader(file_path)
27
+ pages = pdf_loader.load_and_split()
28
+ context = "\n".join(str(page.page_content) for page in pages[:30])
29
+ stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
30
+ stuff_answer = stuff_chain({"input_documents": pages, "question": question, "context": context}, return_only_outputs=True)
31
+ return stuff_answer['output_text']
32
+ else:
33
+ return "Error: Unable to process the document. Please ensure the PDF file is valid."
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
+ def pdf_qa(file, question):
41
+ answer = 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