Chatbot / app.py
NaimaAqeel's picture
Update app.py
0a2bb75 verified
raw
history blame
2.29 kB
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()