Spaces:
Sleeping
Sleeping
File size: 2,781 Bytes
4a1af62 | 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 67 68 69 | 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() |