qa-assistant / app.py
GuidK's picture
Create app.py
4a1af62 verified
import gradio as gr
from transformers import pipeline
# Initialize the question-answering pipeline
qa_model = pipeline('question-answering', model='deepset/roberta-base-squad2')
def get_answer(context, question):
# Check if both inputs are provided
if not context.strip() or not question.strip():
return "Error: Please provide both context and a question."
# Run the model to find the answer
result = qa_model(question=question, context=context)
# Extract the answer text
answer_text = result['answer']
# Calculate the confidence score
confidence = round(result['score'] * 100, 1)
# Return formatted string with answer and probability
return f"{answer_text} (Confidence: {confidence}%)"
# Create Gradio blocks interface
with gr.Blocks(title="QA Assistant", theme=gr.themes.Soft()) as demo:
# Add main header
gr.Markdown("# AI Assistant: Question Answering")
# Add application description
gr.Markdown("Provide a context text and ask a question about it. The AI will analyze the text and extract the exact answer.")
# Create layout with two columns
with gr.Row():
with gr.Column(scale=2):
# Add input box for the context text
input_context = gr.Textbox(
label="Context (Text)",
lines=8,
placeholder="Paste an article or paragraph in English here..."
)
# Add input box for the question
input_question = gr.Textbox(
label="Your Question",
lines=2,
placeholder="What is this text about?"
)
# Add action button
btn_answer = gr.Button("Find Answer", variant='primary')
with gr.Column(scale=1):
# Add output box for the answer
output_answer = gr.Textbox(
label="AI Answer",
lines=4,
interactive=False
)
# Link button click to the answering function
btn_answer.click(
fn=get_answer,
inputs=[input_context, input_question],
outputs=output_answer
)
# Add examples for quick testing
gr.Examples(
examples=[
[
"Python was created by Guido van Rossum and first released in 1991. It is a widely used high-level programming language.",
"Who created Python?"
],
[
"The James Webb Space Telescope (JWST) is a space telescope designed primarily to conduct infrared astronomy. It was launched in December 2021.",
"When was the telescope launched?"
]
],
inputs=[input_context, input_question]
)
if __name__ == '__main__':
demo.launch()