Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -5,34 +5,52 @@ import pdfplumber
|
|
5 |
# Load the pre-trained question-answering model
|
6 |
qa_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
|
7 |
|
8 |
-
|
9 |
-
|
10 |
-
try:
|
11 |
-
# Read and extract text from the uploaded PDF file
|
12 |
-
with pdfplumber.open(file) as pdf:
|
13 |
-
text = ""
|
14 |
-
for page in pdf.pages:
|
15 |
-
text += page.extract_text()
|
16 |
|
17 |
-
|
18 |
-
|
19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
20 |
|
21 |
-
|
22 |
-
|
23 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
24 |
|
25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
fn=answer_question,
|
27 |
-
inputs=
|
28 |
-
gr.File(label="Upload PDF"),
|
29 |
-
gr.Textbox(label="Enter Question", type="text"),
|
30 |
-
gr.Button("Answer"),
|
31 |
-
],
|
32 |
outputs="text",
|
33 |
live=True,
|
34 |
title="PDF Question-Answering",
|
35 |
-
description="
|
36 |
)
|
37 |
|
38 |
-
|
|
|
|
5 |
# Load the pre-trained question-answering model
|
6 |
qa_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
|
7 |
|
8 |
+
# Shared variable to store uploaded PDF text
|
9 |
+
pdf_text = ""
|
|
|
|
|
|
|
|
|
|
|
|
|
10 |
|
11 |
+
# Function to load the PDF and store its text
|
12 |
+
def load_pdf(file):
|
13 |
+
global pdf_text
|
14 |
+
try:
|
15 |
+
with pdfplumber.open(file) as pdf:
|
16 |
+
pdf_text = ""
|
17 |
+
for page in pdf.pages:
|
18 |
+
pdf_text += page.extract_text()
|
19 |
+
return "PDF loaded successfully."
|
20 |
+
except Exception as e:
|
21 |
+
return f"Error processing PDF: {str(e)}"
|
22 |
|
23 |
+
# Function to answer the user's question based on the loaded PDF
|
24 |
+
def answer_question(question):
|
25 |
+
if not pdf_text:
|
26 |
+
return "No PDF loaded. Upload a PDF first."
|
27 |
+
|
28 |
+
try:
|
29 |
+
# Ask the user's question using the question-answering model
|
30 |
+
answer = qa_pipeline({"context": pdf_text, "question": question})
|
31 |
+
return answer["answer"]
|
32 |
+
except Exception as e:
|
33 |
+
return f"Error answering question: {str(e)}"
|
34 |
|
35 |
+
# Interface for uploading the PDF
|
36 |
+
pdf_interface = gr.Interface(
|
37 |
+
fn=load_pdf,
|
38 |
+
inputs=gr.File(label="Upload PDF"),
|
39 |
+
outputs="text",
|
40 |
+
live=True,
|
41 |
+
title="PDF Uploader",
|
42 |
+
description="Upload a PDF to load its content.",
|
43 |
+
)
|
44 |
+
|
45 |
+
# Interface for answering questions based on the loaded PDF
|
46 |
+
qa_interface = gr.Interface(
|
47 |
fn=answer_question,
|
48 |
+
inputs=gr.Textbox(label="Enter Question", type="text"),
|
|
|
|
|
|
|
|
|
49 |
outputs="text",
|
50 |
live=True,
|
51 |
title="PDF Question-Answering",
|
52 |
+
description="Enter a question to get an answer based on the loaded PDF.",
|
53 |
)
|
54 |
|
55 |
+
pdf_interface.launch()
|
56 |
+
qa_interface.launch()
|