import gradio as gr import random # Define questions and answers questions = ["colorful", "worried", "excited", "showing", "respected", "doubters", "success"] answers = ["vibrant", "anxious", "thrilled", "depicting", "admired", "skeptics", "achievement"] answered_questions = set() # Track which questions have been correctly answered 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.", 0 if user_input.strip().lower() == correct_answer.lower(): feedback = "Correct!" score = 1 answered_questions.add(question_index) # Only add to answered if correct 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, score_store=score_store: submit_response(user_input, correct_answer_store.value, question_index_store.value, score_store), inputs=user_input, outputs=[feedback_label, score_store] ) def submit_response(user_input, correct_answer, question_index, score_store): feedback, score = check_answer(user_input, correct_answer, question_index) if score == 1: score_store.value += score # Only accumulate the score if it's a new correct answer return feedback, score_store.value def complete_and_reset(score_store): final_score = score_store.value score_store.value = 0 # Reset the score answered_questions.clear() # Clear the set of answered questions return f"Session Complete. Your final score is {final_score}." complete_button.click( fn=lambda score_store=score_store: complete_and_reset(score_store), inputs=[], outputs=feedback_label ) app.launch()