saritha commited on
Commit
9751da0
·
verified ·
1 Parent(s): 1833a61

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +13 -33
app.py CHANGED
@@ -8,40 +8,20 @@ import gradio as gr
8
  # Function for initialization
9
  def initialize(pdf_file, question):
10
  try:
11
- # Save the uploaded PDF content temporarily
12
- with open("/tmp/uploaded_file.pdf", "wb") as f:
13
- f.write(pdf_file.read())
14
- file_path = "/tmp/uploaded_file.pdf"
15
-
16
- # Configure Google Generative AI
17
- genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
18
- model = genai.GenerativeModel('gemini-pro')
19
- model = ChatGoogleGenerativeAI(model="gemini-pro", temperature=0.3)
20
-
21
- # Prompt template for formatting context and question
22
- 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"
23
-
24
- Context:
25
- {context}
26
-
27
- Question:
28
- {question}
29
-
30
- Answer:
31
- """
32
-
33
- prompt = PromptTemplate(template=prompt_template, input_variables=["context", "question"])
34
-
35
- # Process the PDF if it exists
36
- if os.path.exists(file_path):
37
- pdf_loader = PyPDFLoader(file_path)
38
- pages = pdf_loader.load_and_split()
39
- context = "\n".join(str(page.page_content) for page in pages[:30]) # Limit to first 30 pages
40
- stuff_chain = load_qa_chain(model, chain_type="stuff", prompt=prompt)
41
- stuff_answer = stuff_chain({"input_documents": pages, "question": question, "context": context}, return_only_outputs=True)
42
- return stuff_answer['output_text']
43
  else:
44
- return "Error: Unable to process the document. Please ensure the PDF file is valid."
 
45
  except Exception as e:
46
  return f"An error occurred: {e}" # Generic error handling
47
 
 
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
+ # ... rest of your code for processing the PDF using the file path
20
+ else:
21
+ return "Error: The uploaded file could not be found."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  else:
23
+ return "Error: No PDF file was uploaded."
24
+
25
  except Exception as e:
26
  return f"An error occurred: {e}" # Generic error handling
27