Spaces:
Sleeping
Sleeping
import streamlit as st | |
import time | |
# Sample quiz data (can be generated dynamically via Hugging Face) | |
quiz_data = [ | |
{ | |
"question": "What is the capital of France?", | |
"options": ["Berlin", "Paris", "Madrid", "Rome"], | |
"answer": "Paris" | |
}, | |
{ | |
"question": "What is 2 + 2?", | |
"options": ["3", "4", "5", "6"], | |
"answer": "4" | |
} | |
] | |
st.set_page_config(page_title="AI Quiz App", layout="centered") | |
st.title("π§ AI-Powered Quiz with Timer & Scoring") | |
# Timer per question (in seconds) | |
QUESTION_TIMER = 15 | |
# Session state to store progress | |
if 'current_q' not in st.session_state: | |
st.session_state.current_q = 0 | |
st.session_state.score = 0 | |
st.session_state.start_time = time.time() | |
current_question = quiz_data[st.session_state.current_q] | |
elapsed = time.time() - st.session_state.start_time | |
time_left = max(0, int(QUESTION_TIMER - elapsed)) | |
# Display timer | |
st.info(f"β±οΈ Time Left: {time_left} seconds") | |
if time_left == 0: | |
st.warning("β° Time's up! Moving to next question...") | |
st.session_state.current_q += 1 | |
st.session_state.start_time = time.time() | |
st.experimental_rerun() | |
# Card-style container | |
with st.container(): | |
st.markdown("### β Question:") | |
st.markdown(f"**{current_question['question']}**") | |
selected = st.radio( | |
"Choose your answer:", | |
current_question["options"], | |
index=None, | |
key=st.session_state.current_q | |
) | |
# Submit button | |
if st.button("Submit Answer"): | |
if selected: | |
if selected == current_question["answer"]: | |
st.success("β Correct!") | |
st.session_state.score += 1 | |
else: | |
st.error(f"β Incorrect! Correct answer: {current_question['answer']}") | |
time.sleep(1.5) | |
st.session_state.current_q += 1 | |
st.session_state.start_time = time.time() | |
st.experimental_rerun() | |
else: | |
st.warning("Please select an option before submitting.") | |
# Quiz End | |
if st.session_state.current_q >= len(quiz_data): | |
st.balloons() | |
st.success(f"π Quiz Completed! Your score: {st.session_state.score}/{len(quiz_data)}") | |
if st.button("Restart"): | |
st.session_state.current_q = 0 | |
st.session_state.score = 0 | |
st.session_state.start_time = time.time() | |
st.experimental_rerun() | |