louiecerv commited on
Commit
be2a3d4
·
1 Parent(s): cc871c7

First full save

Browse files
Files changed (3) hide show
  1. app.py +186 -0
  2. quiz_data.db +0 -0
  3. requirements.txt +1 -0
app.py ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import time
3
+ import sqlite3
4
+ import json
5
+ import random
6
+
7
+ # Create a SQLite database to store quiz data
8
+ conn = sqlite3.connect('quiz_data.db')
9
+ c = conn.cursor()
10
+ c.execute('''CREATE TABLE IF NOT EXISTS quiz_history
11
+ (timestamp TEXT, score INTEGER, total_time REAL,
12
+ question_times TEXT, questions TEXT, user_answers TEXT)''')
13
+ conn.commit()
14
+
15
+ # Function to generate random multiple-choice questions
16
+ def generate_questions():
17
+ questions = [
18
+ "What is the capital of France?",
19
+ "What is the largest planet in our solar system?",
20
+ "Who painted the Mona Lisa?",
21
+ "In what year did World War II begin?",
22
+ "What is the chemical symbol for gold?"
23
+ ]
24
+ options = [
25
+ ["Paris", "London", "Berlin", "Madrid"],
26
+ ["Jupiter", "Saturn", "Earth", "Mars"],
27
+ ["Leonardo da Vinci", "Michelangelo", "Raphael", "Donatello"],
28
+ ["1939", "1941", "1945", "1914"],
29
+ ["Au", "Ag", "Fe", "Cu"]
30
+ ]
31
+
32
+ # Create a list of tuples to combine questions and options
33
+ question_option_pairs = list(zip(questions, options))
34
+
35
+ # Shuffle the pairs
36
+ random.shuffle(question_option_pairs)
37
+
38
+ # Unpack the shuffled pairs
39
+ questions, options = zip(*question_option_pairs)
40
+
41
+ return list(questions), list(options)
42
+
43
+ # Function to start a timer
44
+ def start_timer():
45
+ start_time = time.time()
46
+ return start_time
47
+
48
+ # Function to calculate elapsed time
49
+ def calculate_time(start_time):
50
+ elapsed_time = time.time() - start_time
51
+ return elapsed_time
52
+
53
+ def start_quiz_callback():
54
+ st.session_state.quiz_started = True
55
+ st.session_state.questions, st.session_state.options = generate_questions()
56
+ st.session_state.total_start_time = start_timer()
57
+
58
+ def next_question_callback(user_answer):
59
+ st.session_state.user_answers.append(user_answer)
60
+ st.session_state.question_durations.append(calculate_time(st.session_state.item_start_time))
61
+ st.session_state.item_start_time = None
62
+ st.session_state.current_question += 1
63
+
64
+ def show_results_callback():
65
+ st.session_state.total_time = calculate_time(st.session_state.total_start_time)
66
+ # Calculate score
67
+ correct_answers = ["Paris", "Jupiter", "Leonardo da Vinci", "1939", "Au"]
68
+ score = sum([1 for i in range(len(st.session_state.questions)) if st.session_state.user_answers[i] == correct_answers[i]])
69
+
70
+ # Display results
71
+ st.header("Results")
72
+ st.write(f"Your Score: {score}/{len(st.session_state.questions)}")
73
+ st.write(f"Total Time: {st.session_state.total_time:.2f} seconds")
74
+ st.write("Time per Question:")
75
+ for i, duration in enumerate(st.session_state.question_durations):
76
+ st.write(f"Question {i+1}: {duration:.2f} seconds")
77
+
78
+ # Save results to database
79
+ timestamp = time.strftime("%Y-%m-%d %H:%M:%S")
80
+ question_times_json = json.dumps(st.session_state.question_durations)
81
+ questions_json = json.dumps(st.session_state.questions)
82
+ user_answers_json = json.dumps(st.session_state.user_answers)
83
+ c.execute("INSERT INTO quiz_history VALUES (?, ?, ?, ?, ?, ?)",
84
+ (timestamp, score, st.session_state.total_time, question_times_json, questions_json, user_answers_json))
85
+ conn.commit()
86
+
87
+ def delete_attempt_callback(timestamp):
88
+ c.execute("DELETE FROM quiz_history WHERE timestamp=?", (timestamp,))
89
+ conn.commit()
90
+ st.rerun()
91
+
92
+ # Streamlit app
93
+ def main():
94
+ st.title("Sample Quiz App")
95
+
96
+ # Initialize session state variables
97
+ if 'page' not in st.session_state:
98
+ st.session_state.page = "Quiz"
99
+ if 'questions' not in st.session_state:
100
+ st.session_state.questions = None
101
+ if 'options' not in st.session_state:
102
+ st.session_state.options = None
103
+ if 'current_question' not in st.session_state:
104
+ st.session_state.current_question = 0
105
+ if 'user_answers' not in st.session_state:
106
+ st.session_state.user_answers = []
107
+ if 'question_durations' not in st.session_state:
108
+ st.session_state.question_durations = []
109
+ if 'total_start_time' not in st.session_state:
110
+ st.session_state.total_start_time = None
111
+ if 'item_start_time' not in st.session_state:
112
+ st.session_state.item_start_time = None
113
+ if 'quiz_started' not in st.session_state:
114
+ st.session_state.quiz_started = False
115
+
116
+ # Choose between Quiz, History, and About pages
117
+ st.session_state.page = st.sidebar.radio("Select Page", ["Quiz", "History", "About"])
118
+
119
+ if st.session_state.page == "Quiz":
120
+ st.header("Take the Quiz")
121
+
122
+ if not st.session_state.quiz_started:
123
+ if st.button("Start Quiz", key="start_quiz", on_click=start_quiz_callback()):
124
+ pass
125
+ else:
126
+ if st.session_state.current_question < len(st.session_state.questions):
127
+ if st.session_state.item_start_time is None:
128
+ st.session_state.item_start_time = start_timer()
129
+
130
+ st.subheader(f"Question {st.session_state.current_question + 1}")
131
+ st.write(st.session_state.questions[st.session_state.current_question])
132
+ user_answer = st.selectbox("Select your answer:", ["Select an option"] + st.session_state.options[st.session_state.current_question], key="user_answer")
133
+
134
+ if user_answer != "Select an option":
135
+ if st.button("Next", key="next_question", on_click=next_question_callback(user_answer)):
136
+ pass
137
+ else:
138
+ st.warning("Please select an answer.")
139
+ else:
140
+ show_results_callback()
141
+
142
+ elif st.session_state.page == "History":
143
+ st.header("Quiz History")
144
+
145
+ # Retrieve history from database
146
+ c.execute("SELECT * FROM quiz_history")
147
+ rows = c.fetchall()
148
+
149
+ if rows:
150
+ for index, row in enumerate(rows):
151
+ timestamp, score, total_time, question_times_json, questions_json, user_answers_json = row
152
+ question_times = json.loads(question_times_json)
153
+ questions = json.loads(questions_json)
154
+ user_answers = json.loads(user_answers_json)
155
+
156
+ st.write(f"Timestamp: {timestamp}")
157
+ st.write(f"Score: {score}/{len(questions)}")
158
+ st.write(f"Total Time: {total_time:.2f} seconds")
159
+
160
+ st.write("**Summary:**")
161
+ correct_answers = ["Paris", "Jupiter", "Leonardo da Vinci", "1939", "Au"]
162
+ for i, question in enumerate(questions):
163
+ st.write(f"- {question}: {'Correct' if user_answers[i] == correct_answers[i] else 'Incorrect'}")
164
+
165
+ st.write("Time per Question:")
166
+ for i, duration in enumerate(question_times):
167
+ st.write(f"Question {i+1}: {duration:.2f} seconds")
168
+
169
+ if st.button("Delete This Attempt", key=f"{timestamp}_{index}"):
170
+ delete_attempt_callback(timestamp)
171
+ else:
172
+ st.write("No previous quiz attempts found.")
173
+
174
+ elif st.session_state.page == "About":
175
+ st.header("About")
176
+ st.write("This is a simple quiz application for educational purposes.")
177
+ st.write("**Instructions:**")
178
+ st.write("- Select 'Quiz' from the sidebar to begin.")
179
+ st.write("- Click 'Start Quiz' to start the timer and begin the quiz.")
180
+ st.write("- Answer each question and click 'Next' to proceed.")
181
+ st.write("- After completing all questions, your results will be displayed.")
182
+ st.write("- Select 'History' to view your past quiz attempts.")
183
+ st.write("- You can delete individual attempts from the history.")
184
+
185
+ if __name__ == "__main__":
186
+ main()
quiz_data.db ADDED
Binary file (8.19 kB). View file
 
requirements.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ streamlit