Sina Media Lab commited on
Commit
19710ad
Β·
1 Parent(s): 12e8aed
Files changed (1) hide show
  1. app.py +100 -96
app.py CHANGED
@@ -37,10 +37,8 @@ def generate_pdf_report():
37
  pdf.add_page()
38
  pdf.set_font("Arial", style='B', size=18)
39
 
40
- # Title of the report with a link
41
- pdf.set_text_color(0, 0, 255) # Set color to blue for the link
42
- pdf.cell(0, 10, txt="πŸͺ„ Magic Math Quiz!", ln=True, align="C", link="https://huggingface.co/spaces/tofighi/math")
43
- pdf.set_text_color(0, 0, 0) # Reset color to black
44
  pdf.ln(5)
45
 
46
  # Load the image from the URL, scaled down and centered
@@ -113,14 +111,12 @@ def load_modules():
113
  with open(config_path) as f:
114
  exec(f.read(), config)
115
  category_title = config.get("title", category.title().replace("_", " "))
116
- category_description = config.get("description", "No description available.")
117
  order = config.get("order", 100) # Default order is 100 if not specified
118
  else:
119
  category_title = category.title().replace("_", " ")
120
- category_description = "No description available."
121
  order = 100
122
 
123
- modules[category_title] = {"order": order, "description": category_description, "modules": {}}
124
  for filename in os.listdir(category_dir):
125
  if filename.endswith(".py") and filename != "__init__.py" and filename != "config.py":
126
  module_name = filename[:-3]
@@ -155,30 +151,18 @@ modules = load_modules()
155
  st.sidebar.markdown(
156
  """
157
  <div style='background-color: white; padding: 10px; border-radius: 10px; text-align: center; color: black;'>
158
- <h1 style='margin: 0;'>
159
- <a href="https://huggingface.co/spaces/tofighi/math" target="_blank" style="color: black; text-decoration: none;">
160
- πŸͺ„ Magic Math Quiz!<sup>Beta</sup>
161
- </a>
162
- </h1>
163
  <a href="https://ghassem.com" target="_blank">
164
  <img src="https://huggingface.co/spaces/tofighi/math/resolve/main/assets/gt.png" alt="Logo" style="width:50%; margin-top: 10px;">
165
  </a>
166
  </div>
167
  """, unsafe_allow_html=True)
168
 
169
- # Sidebar content
170
  st.sidebar.title("Quiz Categories")
171
  selected_category = st.sidebar.selectbox("Choose a category:", list(modules.keys()))
172
 
173
- # Get category description for tooltip
174
- category_description = modules[selected_category]["description"] if selected_category and selected_category in modules else "No description available."
175
-
176
  if selected_category:
177
- module_options = [modules[selected_category][module]["title"] for module in modules[selected_category]]
178
- selected_module = st.sidebar.radio(
179
- "Choose a module:",
180
- module_options
181
- )
182
 
183
  for module_name, module_data in modules[selected_category].items():
184
  if module_data["title"] == selected_module:
@@ -190,89 +174,109 @@ if selected_category:
190
  with col1:
191
  st.markdown(
192
  f"""
193
- <div style="background-color: #333; color: white; padding: 10px; border-radius: 10px;">
194
- <h2 style="margin: 0;">{selected_category} > {selected_module}</h2>
195
- <p>{selected_module_data['description']}</p>
196
  </div>
197
- """, unsafe_allow_html=True
 
198
  )
 
199
  with col2:
200
- if st.button("Download PDF Report", key="download_pdf"):
201
- st.session_state.pdf_data = generate_pdf_report()
 
 
 
202
  st.download_button(
203
- label="Download PDF Report",
204
  data=st.session_state.pdf_data,
205
- file_name=f"quiz_report_{st.session_state.session_id}.pdf",
206
- mime="application/pdf"
 
 
207
  )
208
 
209
- if selected_module_data:
210
- if st.button(st.session_state.button_label):
211
- if st.session_state.button_label == "Submit":
212
- if st.session_state.selected_answer is not None:
213
- question = st.session_state.questions[st.session_state.current_index]
214
- question['answered'] = True
215
- if st.session_state.selected_answer == question['correct_answer']:
216
- st.session_state.correct_count += 1
217
- st.session_state.module_correct_count[selected_module] = st.session_state.module_correct_count.get(selected_module, 0) + 1
218
- else:
219
- st.session_state.module_correct_count[selected_module] = st.session_state.module_correct_count.get(selected_module, 0)
220
-
221
- st.session_state.questions[st.session_state.current_index] = question
222
- st.session_state.current_index += 1
223
- st.session_state.selected_answer = None
224
- st.session_state.button_label = "Next Question"
225
- st.session_state.pdf_data = None # Reset PDF cache when moving to the next question
226
- else:
227
- st.warning("Please select an answer before submitting.")
228
- elif st.session_state.button_label == "Next Question":
229
- if st.session_state.current_index < len(st.session_state.questions):
230
- question = st.session_state.questions[st.session_state.current_index]
231
- st.session_state.selected_answer = None
232
- st.session_state.button_label = "Submit"
233
- else:
234
- st.session_state.button_label = "Submit/New"
235
- st.session_state.current_index = 0
236
- st.session_state.questions = []
237
- st.session_state.correct_count = 0
238
- st.session_state.module_correct_count = {}
239
- st.session_state.pdf_data = generate_pdf_report()
240
-
241
- st.experimental_rerun()
 
 
 
242
 
243
- if st.session_state.questions:
244
- question = st.session_state.questions[st.session_state.current_index]
245
- st.write(f"**Q{st.session_state.current_index + 1}:** {question['question']}")
246
- options = ['a', 'b', 'c', 'd']
247
- for i, option in enumerate(question['options']):
248
- is_selected = st.session_state.selected_answer == options[i]
 
 
 
 
 
 
 
 
249
  option_text = f"{options[i]}. {option}"
250
- if question['answered']:
251
- if options[i] == question['correct_answer']:
252
- st.markdown(f"<p style='color: green;'>{option_text}</p>", unsafe_allow_html=True)
253
- elif is_selected:
254
- st.markdown(f"<p style='color: red;'>{option_text}</p>", unsafe_allow_html=True)
255
- else:
256
- st.markdown(f"<p>{option_text}</p>", unsafe_allow_html=True)
257
  else:
258
- if is_selected:
259
- st.markdown(f"<p style='color: blue;'>{option_text}</p>", unsafe_allow_html=True)
260
- else:
261
- st.markdown(f"<p>{option_text}</p>", unsafe_allow_html=True)
262
-
263
- if not question['answered']:
264
- if st.radio("Options", options, key=question['question'], index=options.index(st.session_state.selected_answer) if st.session_state.selected_answer else -1) == options[i]:
265
- st.session_state.selected_answer = options[i]
266
- else:
267
- st.write("No questions available.")
268
- else:
269
- st.write("Please select a category and module.")
270
 
271
- # Footer
272
- st.markdown(
273
- """
274
- <div style='text-align: center; color: grey; font-size: 12px;'>
275
- <p>By Ghassem Tofighi</p>
276
- </div>
277
- """, unsafe_allow_html=True
278
- )
 
 
 
 
 
 
 
 
 
 
 
 
37
  pdf.add_page()
38
  pdf.set_font("Arial", style='B', size=18)
39
 
40
+ # Title of the report
41
+ pdf.cell(0, 10, txt="Magic Math Quiz!", ln=True, align="C")
 
 
42
  pdf.ln(5)
43
 
44
  # Load the image from the URL, scaled down and centered
 
111
  with open(config_path) as f:
112
  exec(f.read(), config)
113
  category_title = config.get("title", category.title().replace("_", " "))
 
114
  order = config.get("order", 100) # Default order is 100 if not specified
115
  else:
116
  category_title = category.title().replace("_", " ")
 
117
  order = 100
118
 
119
+ modules[category_title] = {"order": order, "modules": {}}
120
  for filename in os.listdir(category_dir):
121
  if filename.endswith(".py") and filename != "__init__.py" and filename != "config.py":
122
  module_name = filename[:-3]
 
151
  st.sidebar.markdown(
152
  """
153
  <div style='background-color: white; padding: 10px; border-radius: 10px; text-align: center; color: black;'>
154
+ <h1 style='margin: 0;'>πŸͺ„ Magic Math Quiz!<sup>Beta</sup></h1>
 
 
 
 
155
  <a href="https://ghassem.com" target="_blank">
156
  <img src="https://huggingface.co/spaces/tofighi/math/resolve/main/assets/gt.png" alt="Logo" style="width:50%; margin-top: 10px;">
157
  </a>
158
  </div>
159
  """, unsafe_allow_html=True)
160
 
 
161
  st.sidebar.title("Quiz Categories")
162
  selected_category = st.sidebar.selectbox("Choose a category:", list(modules.keys()))
163
 
 
 
 
164
  if selected_category:
165
+ selected_module = st.sidebar.radio("Choose a module:", [modules[selected_category][module]["title"] for module in modules[selected_category]])
 
 
 
 
166
 
167
  for module_name, module_data in modules[selected_category].items():
168
  if module_data["title"] == selected_module:
 
174
  with col1:
175
  st.markdown(
176
  f"""
177
+ <div style="background-color: #333; padding: 10px; border-radius: 5px; margin-top: 20px;">
178
+ <span style='font-size: 18px; color: white;'>{selected_category} > {selected_module_data['title']}</span>
 
179
  </div>
180
+ """,
181
+ unsafe_allow_html=True
182
  )
183
+
184
  with col2:
185
+ # Add some spacing above the button by placing it inside an empty container
186
+ st.markdown("<div style='margin-top: 25px;'></div>", unsafe_allow_html=True) # Increased margin by 5px
187
+ # Show PDF report button, initially disabled until a question is answered
188
+ pdf_disabled = len(st.session_state.questions) == 0
189
+ if st.session_state.pdf_data:
190
  st.download_button(
191
+ label="Quiz Report",
192
  data=st.session_state.pdf_data,
193
+ file_name="quiz_report.pdf",
194
+ mime="application/pdf",
195
+ disabled=False,
196
+ key="pdf_download_button"
197
  )
198
 
199
+ if selected_module != st.session_state.current_module:
200
+ st.session_state.current_module = selected_module
201
+ st.session_state.current_index = len(st.session_state.questions) # Continue numbering from previous questions
202
+ st.session_state.selected_answer = None
203
+ st.session_state.button_label = "Submit/New"
204
+ st.session_state.start_time = time.time() # Start the timer for the new question
205
+ # Initialize question count and correct count if not already done
206
+ if selected_module not in st.session_state.module_question_count:
207
+ st.session_state.module_question_count[selected_module] = 0
208
+ if selected_module not in st.session_state.module_correct_count:
209
+ st.session_state.module_correct_count[selected_module] = 0
210
+ # Generate a new question without adding it to the answered list yet
211
+ st.session_state.current_question = generate_new_question(selected_category, selected_module, selected_module_data)
212
+
213
+ current_question = st.session_state.current_question
214
+
215
+ # Display the current question inside the options box
216
+ with st.form(key=f'question_form_{st.session_state.current_index}'):
217
+ options = ['a', 'b', 'c', 'd']
218
+ st.markdown(f"<b>Q{st.session_state.current_index + 1}: {current_question['question']}</b>", unsafe_allow_html=True)
219
+ selected_answer = st.radio(
220
+ "", # Empty label to put the question inside the options box
221
+ options=[f"{options[i]}. {opt}" for i, opt in enumerate(current_question['options'])],
222
+ key=f"question_{st.session_state.current_index}_options",
223
+ index=None,
224
+ )
225
+
226
+ submit_button = st.form_submit_button(label="Submit/New")
227
+
228
+ # Handle button state and answer submission
229
+ if submit_button:
230
+ if selected_answer is None:
231
+ st.warning("Please select an option before submitting.", icon="⚠️")
232
+ else:
233
+ # Calculate time taken to answer the question
234
+ current_question['time_taken'] = int(time.time() - st.session_state.start_time)
235
 
236
+ # Process the answer
237
+ selected_answer_text = selected_answer.split(". ", 1)[1] # Extract the text part
238
+ current_question['selected'] = selected_answer_text
239
+ current_question['answered'] = True
240
+ st.session_state.module_question_count[selected_module] += 1
241
+
242
+ if selected_answer_text == current_question['correct_answer']:
243
+ st.session_state.correct_count += 1
244
+ st.session_state.module_correct_count[selected_module] += 1
245
+
246
+ # Show correct/incorrect feedback, explanation, and step-by-step solution
247
+ col1, col2 = st.columns(2)
248
+ with col1:
249
+ for i, option in enumerate(current_question['options']):
250
  option_text = f"{options[i]}. {option}"
251
+ if option == current_question['correct_answer']:
252
+ st.markdown(f"<span style='color:green;'>{option_text} βœ…</span>", unsafe_allow_html=True)
253
+ elif option == selected_answer_text:
254
+ st.markdown(f"<span style='color:red;'>{option_text} ❌</span>", unsafe_allow_html=True)
 
 
 
255
  else:
256
+ st.markdown(f"{option_text}", unsafe_allow_html=True)
257
+
258
+ with col2:
259
+ st.markdown(f"<span style='font-size: 14px;'><b>Explanation:</b> {current_question['explanation']}</span>", unsafe_allow_html=True)
260
+ st.markdown(f"<span style='font-size: 14px;'><b>Step-by-Step Solution:</b></span>", unsafe_allow_html=True)
261
+ for step in current_question['step_by_step_solution']:
262
+ st.markdown(f"<span style='font-size: 14px;'>{step}</span>", unsafe_allow_html=True)
 
 
 
 
 
263
 
264
+ # Add the question to the answered list only after submission
265
+ st.session_state.questions.append(current_question)
266
+ st.session_state.current_index = len(st.session_state.questions)
267
+
268
+ # Generate the PDF report data after each submission
269
+ st.session_state.pdf_data = generate_pdf_report()
270
+
271
+ # Refresh the PDF button state
272
+ st.download_button(
273
+ label="Quiz Report",
274
+ data=st.session_state.pdf_data,
275
+ file_name="quiz_report.pdf",
276
+ mime="application/pdf",
277
+ disabled=False,
278
+ key="pdf_download_button_updated"
279
+ )
280
+
281
+ # Generate a new question for the next round
282
+ st.session_state.current_question = generate_new_question(selected_category, selected_module, selected_module_data)