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 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, score, question_index): if question_index in answered_questions: return f"You have already answered this question. Your score remains {score}.", score if user_input.strip().lower() == correct_answer.lower(): score += 1 feedback = f"Correct! Your score is now {score}." else: feedback = f"Incorrect. The correct answer was '{correct_answer}'. Your score remains {score}." answered_questions.add(question_index) return feedback, score with gr.Blocks() as app: with gr.Row(): question_dropdown = gr.Dropdown(choices=questions, label="Select a question", value=questions[0]) 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, score_store=score_store, question_index_store=question_index_store: submit_response(user_input, correct_answer_store.value, score_store.value, question_index_store.value), inputs=user_input, outputs=[feedback_label, score_store] ) def submit_response(user_input, correct_answer, score, question_index): feedback, updated_score = check_answer(user_input, correct_answer, score, question_index) score_store.value = updated_score # Ensure the score is updated in the state return feedback, updated_score 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()