Spaces:
Sleeping
Sleeping
| import streamlit as st | |
| import time | |
| import sqlite3 | |
| import json | |
| import random | |
| # Create a SQLite database to store quiz data | |
| conn = sqlite3.connect('quiz_data.db') | |
| c = conn.cursor() | |
| c.execute('''CREATE TABLE IF NOT EXISTS quiz_history | |
| (timestamp TEXT, score INTEGER, total_time REAL, | |
| question_times TEXT, questions TEXT, user_answers TEXT)''') | |
| conn.commit() | |
| # Function to generate random multiple-choice questions | |
| def generate_questions(): | |
| questions = [ | |
| "What is the capital of France?", | |
| "What is the largest planet in our solar system?", | |
| "Who painted the Mona Lisa?", | |
| "In what year did World War II begin?", | |
| "What is the chemical symbol for gold?" | |
| ] | |
| options = [ | |
| ["Paris", "London", "Berlin", "Madrid"], | |
| ["Jupiter", "Saturn", "Earth", "Mars"], | |
| ["Leonardo da Vinci", "Michelangelo", "Raphael", "Donatello"], | |
| ["1939", "1941", "1945", "1914"], | |
| ["Au", "Ag", "Fe", "Cu"] | |
| ] | |
| # Create a list of tuples to combine questions and options | |
| question_option_pairs = list(zip(questions, options)) | |
| # Shuffle the pairs | |
| random.shuffle(question_option_pairs) | |
| # Unpack the shuffled pairs | |
| questions, options = zip(*question_option_pairs) | |
| return list(questions), list(options) | |
| # Function to start a timer | |
| def start_timer(): | |
| start_time = time.time() | |
| return start_time | |
| # Function to calculate elapsed time | |
| def calculate_time(start_time): | |
| elapsed_time = time.time() - start_time | |
| return elapsed_time | |
| def start_quiz_callback(): | |
| st.session_state.quiz_started = True | |
| st.session_state.questions, st.session_state.options = generate_questions() | |
| st.session_state.total_start_time = start_timer() | |
| def next_question_callback(user_answer): | |
| st.session_state.user_answers.append(user_answer) | |
| st.session_state.question_durations.append(calculate_time(st.session_state.item_start_time)) | |
| st.session_state.item_start_time = None | |
| st.session_state.current_question += 1 | |
| def show_results_callback(): | |
| st.session_state.total_time = calculate_time(st.session_state.total_start_time) | |
| # Calculate score | |
| correct_answers = ["Paris", "Jupiter", "Leonardo da Vinci", "1939", "Au"] | |
| score = sum([1 for i in range(len(st.session_state.questions)) if st.session_state.user_answers[i] == correct_answers[i]]) | |
| # Display results | |
| st.header("Results") | |
| st.write(f"Your Score: {score}/{len(st.session_state.questions)}") | |
| st.write(f"Total Time: {st.session_state.total_time:.2f} seconds") | |
| st.write("Time per Question:") | |
| for i, duration in enumerate(st.session_state.question_durations): | |
| st.write(f"Question {i+1}: {duration:.2f} seconds") | |
| # Save results to database | |
| timestamp = time.strftime("%Y-%m-%d %H:%M:%S") | |
| question_times_json = json.dumps(st.session_state.question_durations) | |
| questions_json = json.dumps(st.session_state.questions) | |
| user_answers_json = json.dumps(st.session_state.user_answers) | |
| c.execute("INSERT INTO quiz_history VALUES (?, ?, ?, ?, ?, ?)", | |
| (timestamp, score, st.session_state.total_time, question_times_json, questions_json, user_answers_json)) | |
| conn.commit() | |
| def delete_attempt_callback(timestamp): | |
| c.execute("DELETE FROM quiz_history WHERE timestamp=?", (timestamp,)) | |
| conn.commit() | |
| st.rerun() | |
| # Streamlit app | |
| def main(): | |
| st.title("Sample Quiz App") | |
| # Initialize session state variables | |
| if 'page' not in st.session_state: | |
| st.session_state.page = "Quiz" | |
| if 'questions' not in st.session_state: | |
| st.session_state.questions = None | |
| if 'options' not in st.session_state: | |
| st.session_state.options = None | |
| if 'current_question' not in st.session_state: | |
| st.session_state.current_question = 0 | |
| if 'user_answers' not in st.session_state: | |
| st.session_state.user_answers = [] | |
| if 'question_durations' not in st.session_state: | |
| st.session_state.question_durations = [] | |
| if 'total_start_time' not in st.session_state: | |
| st.session_state.total_start_time = None | |
| if 'item_start_time' not in st.session_state: | |
| st.session_state.item_start_time = None | |
| if 'quiz_started' not in st.session_state: | |
| st.session_state.quiz_started = False | |
| # Choose between Quiz, History, and About pages | |
| st.session_state.page = st.sidebar.radio("Select Page", ["Quiz", "History", "About"]) | |
| if st.session_state.page == "Quiz": | |
| st.header("Take the Quiz") | |
| if not st.session_state.quiz_started: | |
| if st.button("Start Quiz", key="start_quiz", on_click=start_quiz_callback()): | |
| pass | |
| else: | |
| if st.session_state.current_question < len(st.session_state.questions): | |
| if st.session_state.item_start_time is None: | |
| st.session_state.item_start_time = start_timer() | |
| st.subheader(f"Question {st.session_state.current_question + 1}") | |
| st.write(st.session_state.questions[st.session_state.current_question]) | |
| user_answer = st.selectbox("Select your answer:", ["Select an option"] + st.session_state.options[st.session_state.current_question], key="user_answer") | |
| if user_answer != "Select an option": | |
| if st.button("Next", key="next_question", on_click=next_question_callback(user_answer)): | |
| pass | |
| else: | |
| st.warning("Please select an answer.") | |
| else: | |
| show_results_callback() | |
| elif st.session_state.page == "History": | |
| st.header("Quiz History") | |
| # Retrieve history from database | |
| c.execute("SELECT * FROM quiz_history") | |
| rows = c.fetchall() | |
| if rows: | |
| for index, row in enumerate(rows): | |
| timestamp, score, total_time, question_times_json, questions_json, user_answers_json = row | |
| question_times = json.loads(question_times_json) | |
| questions = json.loads(questions_json) | |
| user_answers = json.loads(user_answers_json) | |
| st.write(f"Timestamp: {timestamp}") | |
| st.write(f"Score: {score}/{len(questions)}") | |
| st.write(f"Total Time: {total_time:.2f} seconds") | |
| st.write("**Summary:**") | |
| correct_answers = ["Paris", "Jupiter", "Leonardo da Vinci", "1939", "Au"] | |
| for i, question in enumerate(questions): | |
| st.write(f"- {question}: {'Correct' if user_answers[i] == correct_answers[i] else 'Incorrect'}") | |
| st.write("Time per Question:") | |
| for i, duration in enumerate(question_times): | |
| st.write(f"Question {i+1}: {duration:.2f} seconds") | |
| if st.button("Delete This Attempt", key=f"{timestamp}_{index}"): | |
| delete_attempt_callback(timestamp) | |
| else: | |
| st.write("No previous quiz attempts found.") | |
| elif st.session_state.page == "About": | |
| st.header("About") | |
| st.write("This is a simple quiz application for educational purposes.") | |
| st.write("**Instructions:**") | |
| st.write("- Select 'Quiz' from the sidebar to begin.") | |
| st.write("- Click 'Start Quiz' to start the timer and begin the quiz.") | |
| st.write("- Answer each question and click 'Next' to proceed.") | |
| st.write("- After completing all questions, your results will be displayed.") | |
| st.write("- Select 'History' to view your past quiz attempts.") | |
| st.write("- You can delete individual attempts from the history.") | |
| if __name__ == "__main__": | |
| main() |