admin08077 commited on
Commit
16a7e13
Β·
verified Β·
1 Parent(s): d7ad4b8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -72
app.py CHANGED
@@ -9,14 +9,24 @@ st.set_page_config(page_title="πŸ“š Multiple Choice Test Creator", layout="wide"
9
  if 'tests' not in st.session_state:
10
  st.session_state['tests'] = []
11
 
12
- # Function to add a new test
13
- def add_test(test_title, questions):
14
- test = {
15
- 'title': test_title,
16
- 'questions': questions
17
- }
18
- st.session_state['tests'].append(test)
19
- st.success(f"Test '{test_title}' created successfully!")
 
 
 
 
 
 
 
 
 
 
20
 
21
  # Function to generate HTML content for the test
22
  def generate_html(test_title, questions):
@@ -77,24 +87,6 @@ with tabs[0]:
77
  # Input for Test Title
78
  test_title = st.text_input("Enter Test Title", "")
79
 
80
- # Container for questions
81
- questions_container = st.container()
82
-
83
- # Initialize session state for questions if not present
84
- if 'current_questions' not in st.session_state:
85
- st.session_state['current_questions'] = []
86
-
87
- # Function to add a new question
88
- def add_question():
89
- if len(st.session_state['current_questions']) < 10:
90
- st.session_state['current_questions'].append({
91
- 'question': '',
92
- 'options': {'A': '', 'B': '', 'C': '', 'D': ''},
93
- 'correct': 'A'
94
- })
95
- else:
96
- st.warning("You can only add up to 10 questions.")
97
-
98
  # Button to add a new question
99
  st.button("βž• Add a Question", on_click=add_question)
100
 
@@ -102,41 +94,28 @@ with tabs[0]:
102
  for idx, q in enumerate(st.session_state['current_questions']):
103
  with st.expander(f"Question {idx + 1}", expanded=True):
104
  # Question Text
105
- st.text_input("Question Text", value=q['question'], key=f"question_{idx}",
106
- on_change=lambda i=idx: st.session_state['current_questions'].__setitem__(
107
- i,
108
- {'question': st.session_state[f"question_{i}"],
109
- 'options': st.session_state['current_questions'][i]['options'],
110
- 'correct': st.session_state['current_questions'][i]['correct']}
111
- ))
112
 
113
  # Answer Options
114
  for option in ['A', 'B', 'C', 'D']:
115
- st.text_input(f"Answer {option}", value=q['options'][option], key=f"question_{idx}_option_{option}",
116
- on_change=lambda o=option, i=idx: st.session_state['current_questions'].__setitem__(
117
- i,
118
- {
119
- 'question': st.session_state[f"question_{i}"],
120
- 'options': {**st.session_state['current_questions'][i]['options'], o: st.session_state[f"question_{i}_option_{o}"]},
121
- 'correct': st.session_state['current_questions'][i]['correct']
122
- }
123
- ))
124
 
125
  # Correct Answer Selector
126
- correct_option = st.selectbox("Select Correct Answer", options=['A', 'B', 'C', 'D'],
 
127
  index=['A','B','C','D'].index(q['correct']),
128
- key=f"question_{idx}_correct",
129
- on_change=lambda c='A', i=idx: st.session_state['current_questions'].__setitem__(
130
- i,
131
- {
132
- 'question': st.session_state[f"question_{i}"],
133
- 'options': st.session_state['current_questions'][i]['options'],
134
- 'correct': st.session_state[f"question_{i}_correct"]
135
- }
136
- ))
137
- # Update the correct answer in session_state
138
  st.session_state['current_questions'][idx]['correct'] = correct_option
139
 
 
 
 
 
 
140
  # Button to create the test
141
  if st.button("βœ… Create Test"):
142
  if not test_title:
@@ -152,17 +131,26 @@ with tabs[0]:
152
  incomplete = True
153
  break
154
  if not incomplete:
155
- add_test(test_title, st.session_state['current_questions'])
 
 
 
 
 
 
 
156
  # Clear current questions after creation
157
  st.session_state['current_questions'] = []
 
158
  # Provide download button
159
- html_content = generate_html(test_title, st.session_state['tests'][-1]['questions'])
160
  st.download_button(
161
  label="πŸ“„ Download Test as HTML",
162
  data=html_content,
163
  file_name=f"{test_title.replace(' ', '_')}.html",
164
  mime="text/html"
165
  )
 
166
  # Optionally, display the test
167
  st.markdown("---")
168
  st.header("πŸ“ Your Test")
@@ -186,18 +174,27 @@ with tabs[1]:
186
  # Initialize session state for user answers if not present
187
  if 'user_answers' not in st.session_state:
188
  st.session_state['user_answers'] = {}
189
-
190
  with st.form("take_test_form"):
191
- for idx, q in enumerate(selected_test['questions'], 1):
192
  st.markdown(f"**{idx}. {q['question']}**")
 
 
 
 
 
 
 
 
193
  answer = st.radio(
194
  f"Select an answer for Question {idx}",
195
- options=['A', 'B', 'C', 'D'],
196
  key=f"test_{selected_test_title}_q{idx}"
197
  )
198
- st.session_state['user_answers'][idx] = answer
 
199
  st.markdown("---")
200
-
201
  # Submit button
202
  submit = st.form_submit_button("Submit Test")
203
 
@@ -205,20 +202,25 @@ with tabs[1]:
205
  # Grade the test
206
  score = 0
207
  total = len(selected_test['questions'])
208
- for idx, q in enumerate(selected_test['questions'], 1):
209
- if st.session_state['user_answers'][idx] == q['correct']:
 
 
 
 
210
  score += 1
 
 
 
211
 
212
  # Display the result
213
  st.success(f"You scored {score} out of {total}.")
214
 
215
- # Optionally, display correct answers
216
- with st.expander("View Correct Answers"):
217
- for idx, q in enumerate(selected_test['questions'], 1):
218
- user_ans = st.session_state['user_answers'][idx]
219
- correct_ans = q['correct']
220
- is_correct = user_ans == correct_ans
221
- result = "βœ… Correct" if is_correct else f"❌ Incorrect (Correct Answer: {correct_ans})"
222
- st.markdown(f"**{idx}. {q['question']}**")
223
- st.markdown(f"Your Answer: {user_ans} - {result}")
224
- st.markdown("---")
 
9
  if 'tests' not in st.session_state:
10
  st.session_state['tests'] = []
11
 
12
+ # Initialize session state for current questions being added
13
+ if 'current_questions' not in st.session_state:
14
+ st.session_state['current_questions'] = []
15
+
16
+ # Function to add a new question
17
+ def add_question():
18
+ if len(st.session_state['current_questions']) < 10:
19
+ st.session_state['current_questions'].append({
20
+ 'question': '',
21
+ 'options': {'A': '', 'B': '', 'C': '', 'D': ''},
22
+ 'correct': 'A'
23
+ })
24
+ else:
25
+ st.warning("You can only add up to 10 questions.")
26
+
27
+ # Function to remove a question
28
+ def remove_question(index):
29
+ st.session_state['current_questions'].pop(index)
30
 
31
  # Function to generate HTML content for the test
32
  def generate_html(test_title, questions):
 
87
  # Input for Test Title
88
  test_title = st.text_input("Enter Test Title", "")
89
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  # Button to add a new question
91
  st.button("βž• Add a Question", on_click=add_question)
92
 
 
94
  for idx, q in enumerate(st.session_state['current_questions']):
95
  with st.expander(f"Question {idx + 1}", expanded=True):
96
  # Question Text
97
+ question_key = f"question_{idx}"
98
+ question_text = st.text_input("Question Text", value=q['question'], key=question_key)
99
+ st.session_state['current_questions'][idx]['question'] = question_text
 
 
 
 
100
 
101
  # Answer Options
102
  for option in ['A', 'B', 'C', 'D']:
103
+ option_key = f"question_{idx}_option_{option}"
104
+ option_text = st.text_input(f"Answer {option}", value=q['options'][option], key=option_key)
105
+ st.session_state['current_questions'][idx]['options'][option] = option_text
 
 
 
 
 
 
106
 
107
  # Correct Answer Selector
108
+ correct_option_key = f"question_{idx}_correct"
109
+ correct_option = st.selectbox("Select Correct Answer", options=['A', 'B', 'C', 'D'],
110
  index=['A','B','C','D'].index(q['correct']),
111
+ key=correct_option_key)
 
 
 
 
 
 
 
 
 
112
  st.session_state['current_questions'][idx]['correct'] = correct_option
113
 
114
+ # Remove Question Button
115
+ if st.button("πŸ—‘οΈ Remove", key=f"remove_{idx}"):
116
+ remove_question(idx)
117
+ st.experimental_rerun()
118
+
119
  # Button to create the test
120
  if st.button("βœ… Create Test"):
121
  if not test_title:
 
131
  incomplete = True
132
  break
133
  if not incomplete:
134
+ # Add the test to the session state
135
+ test = {
136
+ 'title': test_title,
137
+ 'questions': st.session_state['current_questions'].copy()
138
+ }
139
+ st.session_state['tests'].append(test)
140
+ st.success(f"Test '{test_title}' created successfully!")
141
+
142
  # Clear current questions after creation
143
  st.session_state['current_questions'] = []
144
+
145
  # Provide download button
146
+ html_content = generate_html(test_title, test['questions'])
147
  st.download_button(
148
  label="πŸ“„ Download Test as HTML",
149
  data=html_content,
150
  file_name=f"{test_title.replace(' ', '_')}.html",
151
  mime="text/html"
152
  )
153
+
154
  # Optionally, display the test
155
  st.markdown("---")
156
  st.header("πŸ“ Your Test")
 
174
  # Initialize session state for user answers if not present
175
  if 'user_answers' not in st.session_state:
176
  st.session_state['user_answers'] = {}
177
+
178
  with st.form("take_test_form"):
179
+ for idx, q in enumerate(selected_test['questions'], start=1):
180
  st.markdown(f"**{idx}. {q['question']}**")
181
+ # Prepare options with letters and text
182
+ option_list = [
183
+ f"A. {q['options']['A']}",
184
+ f"B. {q['options']['B']}",
185
+ f"C. {q['options']['C']}",
186
+ f"D. {q['options']['D']}"
187
+ ]
188
+ # Create radio buttons with the full option text
189
  answer = st.radio(
190
  f"Select an answer for Question {idx}",
191
+ options=option_list,
192
  key=f"test_{selected_test_title}_q{idx}"
193
  )
194
+ # Store the selected answer's letter
195
+ st.session_state['user_answers'][idx] = answer.split(".")[0].strip()
196
  st.markdown("---")
197
+
198
  # Submit button
199
  submit = st.form_submit_button("Submit Test")
200
 
 
202
  # Grade the test
203
  score = 0
204
  total = len(selected_test['questions'])
205
+ feedback = []
206
+ for idx, q in enumerate(selected_test['questions'], start=1):
207
+ user_ans = st.session_state['user_answers'].get(idx, None)
208
+ correct_ans = q['correct']
209
+ is_correct = user_ans == correct_ans
210
+ if is_correct:
211
  score += 1
212
+ feedback.append(f"**Question {idx}**: Correct βœ…")
213
+ else:
214
+ feedback.append(f"**Question {idx}**: Incorrect ❌ (Correct Answer: {correct_ans})")
215
 
216
  # Display the result
217
  st.success(f"You scored {score} out of {total}.")
218
 
219
+ # Display feedback
220
+ with st.expander("View Feedback"):
221
+ for fb in feedback:
222
+ st.markdown(fb)
223
+
224
+ # Optionally, clear answers for next test
225
+ st.session_state['user_answers'] = {}
226
+