Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import pdfplumber
|
3 |
+
from transformers import pipeline
|
4 |
+
|
5 |
+
qa_pipeline = pipeline("question-answering", model="distilbert-base-uncased-distilled-squad")
|
6 |
+
|
7 |
+
def extract_text_from_pdf(file):
|
8 |
+
with pdfplumber.open(file.name) as pdf:
|
9 |
+
return "\n".join(page.extract_text() or '' for page in pdf.pages)
|
10 |
+
|
11 |
+
def answer_question(file, question):
|
12 |
+
if file.name.endswith('.pdf'):
|
13 |
+
context = extract_text_from_pdf(file)
|
14 |
+
elif file.name.endswith('.txt'):
|
15 |
+
context = file.read().decode("utf-8")
|
16 |
+
else:
|
17 |
+
return "Unsupported file format. Please upload a PDF or .txt file."
|
18 |
+
|
19 |
+
if not question.strip():
|
20 |
+
return "Please enter a question."
|
21 |
+
|
22 |
+
result = qa_pipeline(question=question, context=context)
|
23 |
+
return result["answer"]
|
24 |
+
with gr.Blocks() as demo:
|
25 |
+
gr.Markdown("## 📄 Document Question Answering with DistilBERT")
|
26 |
+
with gr.Row():
|
27 |
+
file_input = gr.File(label="Upload a PDF or TXT file")
|
28 |
+
question_input = gr.Textbox(label="Ask a question", placeholder="e.g. What is the main topic?")
|
29 |
+
answer_output = gr.Textbox(label="Answer", placeholder="The answer will appear here.")
|
30 |
+
|
31 |
+
submit_btn = gr.Button("Get Answer")
|
32 |
+
|
33 |
+
submit_btn.click(fn=answer_question, inputs=[file_input, question_input], outputs=answer_output)
|
34 |
+
|
35 |
+
demo.launch()
|