Sbaig3229 commited on
Commit
f89c9c1
·
1 Parent(s): 211e1b7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -17
app.py CHANGED
@@ -5,32 +5,47 @@ import pdfplumber
5
  # Load the pre-trained question-answering model
6
  qa_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
7
 
8
- def answer_question(file, ques: str):
9
- try:
10
- # Read and extract text from the uploaded PDF file
11
- with pdfplumber.open(file) as pdf:
12
- text = ""
13
- for page in pdf.pages:
14
- text += page.extract_text()
15
 
16
- # Ask a default question
17
- question = ques
 
 
 
 
 
18
 
19
- # Ask the question using the question-answering model
20
- answer = qa_pipeline({"context": text, "question": question})
 
 
 
21
 
 
 
 
 
 
 
22
  return answer["answer"]
23
 
24
- except Exception as e:
25
- return f"Error processing PDF: {str(e)}"
26
 
27
  iface = gr.Interface(
28
- fn=answer_question,
29
- inputs=gr.File(label="Upload PDF"),
 
 
 
 
 
 
30
  outputs="text",
31
  live=True,
32
- title="PDF Documents Question-Answering",
33
- description="Ask a question about the contents of the uploaded PDF file.",
34
  )
35
 
36
  iface.launch()
 
5
  # Load the pre-trained question-answering model
6
  qa_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
7
 
8
+ class PDFQuestionAnswering:
9
+ def __init__(self):
10
+ self.text = ""
 
 
 
 
11
 
12
+ def load_pdf(self, file):
13
+ try:
14
+ # Read and extract text from the uploaded PDF file
15
+ with pdfplumber.open(file) as pdf:
16
+ self.text = ""
17
+ for page in pdf.pages:
18
+ self.text += page.extract_text()
19
 
20
+ return "PDF loaded successfully."
21
+
22
+ except Exception as e:
23
+ # Handle exceptions, e.g., invalid PDF or other errors
24
+ return f"Error processing PDF: {str(e)}"
25
 
26
+ def answer_question(self, question):
27
+ if not self.text:
28
+ return "No PDF loaded. Upload a PDF first."
29
+
30
+ # Ask the question using the question-answering model
31
+ answer = qa_pipeline({"context": self.text, "question": question})
32
  return answer["answer"]
33
 
34
+ pdf_qa = PDFQuestionAnswering()
 
35
 
36
  iface = gr.Interface(
37
+ fn_map={
38
+ "Load PDF": pdf_qa.load_pdf,
39
+ "Answer Question": pdf_qa.answer_question,
40
+ },
41
+ inputs=[
42
+ gr.File(label="Upload PDF", type="file"),
43
+ gr.Textbox(label="Enter Question", type="text"),
44
+ ],
45
  outputs="text",
46
  live=True,
47
+ title="PDF Question-Answering",
48
+ description="Upload a PDF, load it, and ask questions about its contents.",
49
  )
50
 
51
  iface.launch()