admin08077 commited on
Commit
d7ad4b8
Β·
verified Β·
1 Parent(s): 83ec974

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +169 -85
app.py CHANGED
@@ -1,30 +1,24 @@
1
  import streamlit as st
2
- import json
3
  from io import StringIO
 
4
 
5
  # Set the page configuration
6
- st.set_page_config(page_title="Multiple Choice Test Creator", layout="wide")
7
-
8
- # Initialize session state for questions
9
- if 'questions' not in st.session_state:
10
- st.session_state['questions'] = []
11
-
12
- # Function to add a new question
13
- def add_question():
14
- if len(st.session_state['questions']) < 10:
15
- st.session_state['questions'].append({
16
- 'question': '',
17
- 'options': {'A': '', 'B': '', 'C': '', 'D': ''},
18
- 'correct': 'A'
19
- })
20
- else:
21
- st.warning("You can only add up to 10 questions.")
22
 
23
- # Function to remove a question
24
- def remove_question(index):
25
- st.session_state['questions'].pop(index)
26
 
27
- # Function to generate HTML content
 
 
 
 
 
 
 
 
 
28
  def generate_html(test_title, questions):
29
  html_content = f"""<!DOCTYPE html>
30
  <html>
@@ -73,68 +67,158 @@ def generate_html(test_title, questions):
73
  """
74
  return html_content
75
 
76
- # Title of the app
77
- st.title("πŸ“š Multiple Choice Test Creator")
78
-
79
- # Input for Test Title
80
- st.header("Create a New Test")
81
- test_title = st.text_input("Test Title", "")
82
-
83
- # Button to add a new question
84
- st.button("βž• Add a Question", on_click=add_question)
85
-
86
- # Display existing questions
87
- for idx, q in enumerate(st.session_state['questions']):
88
- with st.expander(f"Question {idx + 1}", expanded=True):
89
- col1, col2 = st.columns([4,1])
90
- with col1:
91
- st.text_input(f"Question {idx + 1} Text", value=q['question'], key=f"question_{idx}", on_change=lambda i=idx: st.session_state['questions'].__setitem__(i, {'question': st.session_state[f'question_{i}'], 'options': st.session_state['questions'][i]['options'], 'correct': st.session_state['questions'][i]['correct']}))
92
- with col2:
93
- if st.button("πŸ—‘οΈ Remove", key=f"remove_{idx}"):
94
- remove_question(idx)
95
- st.experimental_rerun()
96
-
97
- # Options for answers
98
- for option in ['A', 'B', 'C', 'D']:
99
- st.text_input(f"Answer {option}", value=q['options'][option], key=f"question_{idx}_option_{option}", on_change=lambda o=option, i=idx: st.session_state['questions'].__setitem__(i, {
100
- 'question': st.session_state[f'question_{i}'],
101
- 'options': {**st.session_state['questions'][i]['options'], o: st.session_state[f'question_{i}_option_{o}']},
102
- 'correct': st.session_state['questions'][i]['correct']
103
- }))
104
-
105
- # Correct answer selector
106
- correct_option = st.selectbox("Select Correct Answer", options=['A', 'B', 'C', 'D'], index=['A','B','C','D'].index(q['correct']), key=f"question_{idx}_correct", on_change=lambda c='A', i=idx: st.session_state['questions'].__setitem__(i, {
107
- 'question': st.session_state[f'question_{i}'],
108
- 'options': st.session_state['questions'][i]['options'],
109
- 'correct': st.session_state[f'question_{i}_correct']
110
- }))
111
- # Update the correct answer in session_state
112
- st.session_state['questions'][idx]['correct'] = correct_option
113
-
114
- # Button to generate and download the test
115
- if st.button("πŸ“₯ Generate and Download Test"):
116
- if not test_title:
117
- st.error("Please enter a test title.")
118
- elif len(st.session_state['questions']) == 0:
119
- st.error("Please add at least one question.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  else:
121
- # Validate that all questions have all fields filled
122
- incomplete = False
123
- for idx, q in enumerate(st.session_state['questions'], 1):
124
- if not q['question'] or not all(q['options'][opt] for opt in ['A','B','C','D']):
125
- st.error(f"Question {idx} is incomplete. Please fill in all fields.")
126
- incomplete = True
127
- break
128
- if not incomplete:
129
- html_content = generate_html(test_title, st.session_state['questions'])
130
- # Provide download button
131
- st.download_button(
132
- label="πŸ“„ Download Test as HTML",
133
- data=html_content,
134
- file_name=f"{test_title.replace(' ', '_')}.html",
135
- mime="text/html"
136
- )
137
- # Optionally, display the test
138
- st.markdown("---")
139
- st.header("πŸ“ Your Test")
140
- st.markdown(html_content, unsafe_allow_html=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
 
2
  from io import StringIO
3
+ import json
4
 
5
  # Set the page configuration
6
+ st.set_page_config(page_title="πŸ“š Multiple Choice Test Creator", layout="wide")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
 
8
+ # Initialize session state for storing tests
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):
23
  html_content = f"""<!DOCTYPE html>
24
  <html>
 
67
  """
68
  return html_content
69
 
70
+ # Tabs for navigation
71
+ tabs = st.tabs(["πŸ“ Create Test", "πŸ“– Take Test"])
72
+
73
+ # -------------------- Create Test Tab -------------------- #
74
+ with tabs[0]:
75
+ st.header("Create a New Multiple-Choice Test")
76
+
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
+
101
+ # Display existing questions
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:
143
+ st.error("Please enter a test title.")
144
+ elif len(st.session_state['current_questions']) == 0:
145
+ st.error("Please add at least one question.")
146
+ else:
147
+ # Validate that all questions have all fields filled
148
+ incomplete = False
149
+ for idx, q in enumerate(st.session_state['current_questions'], 1):
150
+ if not q['question'] or not all(q['options'][opt] for opt in ['A','B','C','D']):
151
+ st.error(f"Question {idx} is incomplete. Please fill in all fields.")
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")
169
+ st.markdown(html_content, unsafe_allow_html=True)
170
+
171
+ # -------------------- Take Test Tab -------------------- #
172
+ with tabs[1]:
173
+ st.header("Take a Multiple-Choice Test")
174
+
175
+ if len(st.session_state['tests']) == 0:
176
+ st.info("No tests available. Please create a test first.")
177
  else:
178
+ # Select a test to take
179
+ test_titles = [test['title'] for test in st.session_state['tests']]
180
+ selected_test_title = st.selectbox("Select a Test to Take", options=test_titles)
181
+
182
+ # Retrieve the selected test
183
+ selected_test = next((test for test in st.session_state['tests'] if test['title'] == selected_test_title), None)
184
+
185
+ if selected_test:
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
+
204
+ if submit:
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("---")