Spaces:
Runtime error
Runtime error
File size: 2,285 Bytes
834c71a 0a2bb75 944d263 834c71a 0a2bb75 944d263 0a2bb75 944d263 0a2bb75 a028e27 0a2bb75 a028e27 0a2bb75 a028e27 0a2bb75 9502a66 0a2bb75 072e16f 0a2bb75 a028e27 0a2bb75 a028e27 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
import gradio as gr
from PyPDF2 import PdfReader
from transformers import pipeline
# Load QA pipeline
qa_pipeline = pipeline("question-answering", model="distilbert-base-cased-distilled-squad")
# Function to extract text from PDF
def extract_text_from_pdf(file):
reader = PdfReader(file)
text = ''
for page in reader.pages:
content = page.extract_text()
if content:
text += content
return text
# Store context globally
document_context = {"text": ""}
# Function to set context from PDF or text
def set_context(pdf_file, text_input):
if pdf_file:
extracted = extract_text_from_pdf(pdf_file)
document_context["text"] = extracted
return "PDF uploaded and processed successfully!"
elif text_input.strip():
document_context["text"] = text_input.strip()
return "Text received and stored successfully!"
else:
return "Please upload a PDF or provide some text."
# Function to answer questions based on stored context
def answer_question(question):
context = document_context["text"]
if not context:
return "Please upload a document or enter some text first."
if not question.strip():
return "Please enter a question."
try:
result = qa_pipeline(question=question, context=context)
return result["answer"]
except Exception as e:
return f"Error during QA: {str(e)}"
# Gradio Interface
with gr.Blocks() as demo:
gr.Markdown("# 📄 Ask Questions from a Document")
gr.Markdown("Upload a PDF or paste some text, then ask questions about it!")
with gr.Row():
pdf_input = gr.File(label="Upload PDF (optional)", type="binary")
text_input = gr.Textbox(label="Or paste text here", lines=8, placeholder="Paste your document text...")
upload_btn = gr.Button("Submit Document")
upload_output = gr.Textbox(label="Status", interactive=False)
question_input = gr.Textbox(label="Ask a Question", placeholder="Type your question here...")
answer_output = gr.Textbox(label="Answer", interactive=False)
upload_btn.click(set_context, inputs=[pdf_input, text_input], outputs=upload_output)
question_input.change(answer_question, inputs=question_input, outputs=answer_output)
demo.launch()
|