|
import gradio as gr |
|
import random |
|
|
|
|
|
questions = ["colorful", "worried", "excited", "showing", "respected", "doubters", "success"] |
|
answers = ["vibrant", "anxious", "thrilled", "depicting", "admired", "skeptics", "achievement"] |
|
|
|
answered_questions = set() |
|
|
|
def get_options(question): |
|
index = questions.index(question) |
|
correct_answer = answers[index] |
|
options = set([correct_answer]) |
|
while len(options) < 4: |
|
options.add(random.choice(answers)) |
|
options = list(options) |
|
random.shuffle(options) |
|
return ", ".join(options), correct_answer, index |
|
|
|
def check_answer(user_input, correct_answer, question_index): |
|
if question_index in answered_questions: |
|
return "Correct! You have already answered this question correctly.", 1 |
|
if user_input.strip().lower() == correct_answer.lower(): |
|
feedback = "Correct!" |
|
score = 1 |
|
answered_questions.add(question_index) |
|
else: |
|
feedback = f"Incorrect. The correct answer was '{correct_answer}'." |
|
score = 0 |
|
return feedback, score |
|
|
|
with gr.Blocks() as app: |
|
with gr.Row(): |
|
question_dropdown = gr.Dropdown(choices=questions, label="Select a question") |
|
show_options_button = gr.Button("Show me options") |
|
options_output = gr.Textbox(label="Options", interactive=False) |
|
correct_answer_store = gr.State() |
|
question_index_store = gr.State() |
|
user_input = gr.Textbox(label="Type your answer here", visible=True) |
|
submit_button = gr.Button("Submit Answer", visible=True) |
|
feedback_label = gr.Label() |
|
score_store = gr.State(value=0) |
|
complete_button = gr.Button("Complete and Show Total Score", visible=True) |
|
|
|
def show_options(question): |
|
options, correct, index = get_options(question) |
|
options_output.value = options |
|
correct_answer_store.value = correct |
|
question_index_store.value = index |
|
return options, correct, index |
|
|
|
show_options_button.click( |
|
fn=show_options, |
|
inputs=[question_dropdown], |
|
outputs=[options_output, correct_answer_store, question_index_store] |
|
) |
|
|
|
submit_button.click( |
|
fn=lambda user_input, correct_answer_store=correct_answer_store, question_index_store=question_index_store: submit_response(user_input, correct_answer_store.value, question_index_store.value), |
|
inputs=user_input, |
|
outputs=[feedback_label] |
|
) |
|
|
|
def submit_response(user_input, correct_answer, question_index): |
|
feedback, score = check_answer(user_input, correct_answer, question_index) |
|
score_store.value += score |
|
return feedback |
|
|
|
complete_button.click( |
|
fn=lambda score_store=score_store: f"Session Complete. Your final score is {score_store.value}.", |
|
inputs=[], |
|
outputs=feedback_label |
|
) |
|
|
|
app.launch() |
|
|