Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -7,9 +7,8 @@ from datetime import timedelta
|
|
| 7 |
# NOTE: page config called once at top. The title shows "Choose Quiz 1" as requested.
|
| 8 |
st.set_page_config(page_title="Lesson 1 - Part 1 - Choose Quiz 1", page_icon="🚀")
|
| 9 |
|
| 10 |
-
st.title("
|
| 11 |
-
st.write("
|
| 12 |
-
st.write("Note: Quiz 1 for lesson 1 part 1, Quiz 2 for lesson 1 part 2, Quiz 3 for lesson 2 part 1,...")
|
| 13 |
|
| 14 |
# --------------------------
|
| 15 |
# Configuration: timer
|
|
@@ -29,13 +28,11 @@ except Exception:
|
|
| 29 |
FIREBASE_URL = None
|
| 30 |
FIREBASE_AUTH = None
|
| 31 |
|
| 32 |
-
# helper
|
|
|
|
| 33 |
def format_seconds(s):
|
| 34 |
return str(timedelta(seconds=int(s)))
|
| 35 |
|
| 36 |
-
# --------------------------
|
| 37 |
-
# Helpers to load/save from Firebase
|
| 38 |
-
# --------------------------
|
| 39 |
|
| 40 |
def firebase_get(path: str):
|
| 41 |
if not FIREBASE_URL or not FIREBASE_AUTH:
|
|
@@ -64,14 +61,48 @@ def firebase_put(path: str, payload):
|
|
| 64 |
st.error(f"Error saving to {path} in Firebase: {e}")
|
| 65 |
return False
|
| 66 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
# --------------------------
|
| 68 |
-
# Quiz
|
| 69 |
# --------------------------
|
| 70 |
|
| 71 |
def build_quiz_from_master(master_quiz_data):
|
| 72 |
"""Expect master_quiz_data to have a 'questions' field which may be a list or dict of question objects.
|
| 73 |
-
Each question object expected fields: 'question' (string), 'options' (list of 4), 'correct' (index 0..3)
|
| 74 |
-
Returns list of dicts: { 'q':..., 'options':[...], 'correct':<correct_option_string> }
|
| 75 |
"""
|
| 76 |
if master_quiz_data is None:
|
| 77 |
return None
|
|
@@ -80,14 +111,10 @@ def build_quiz_from_master(master_quiz_data):
|
|
| 80 |
if isinstance(master_quiz_data, dict) and "questions" in master_quiz_data:
|
| 81 |
questions_raw = master_quiz_data["questions"]
|
| 82 |
else:
|
| 83 |
-
# maybe the structure is the questions object itself
|
| 84 |
questions_raw = master_quiz_data
|
| 85 |
|
| 86 |
-
# Normalize to ordered list of 10
|
| 87 |
qs = []
|
| 88 |
if isinstance(questions_raw, dict):
|
| 89 |
-
# dict keyed by indices (strings or ints)
|
| 90 |
-
# sort by numeric key when possible
|
| 91 |
try:
|
| 92 |
items = sorted(questions_raw.items(), key=lambda kv: int(kv[0]))
|
| 93 |
except Exception:
|
|
@@ -103,9 +130,7 @@ def build_quiz_from_master(master_quiz_data):
|
|
| 103 |
q_text = q.get("question") if isinstance(q, dict) else None
|
| 104 |
options = q.get("options") if isinstance(q, dict) else None
|
| 105 |
correct_idx = q.get("correct") if isinstance(q, dict) else None
|
| 106 |
-
# Some Firebase exports might store options as dict with numeric keys
|
| 107 |
if isinstance(options, dict):
|
| 108 |
-
# turn into list by numeric order
|
| 109 |
try:
|
| 110 |
items = sorted(options.items(), key=lambda kv: int(kv[0]))
|
| 111 |
options = [it[1] for it in items]
|
|
@@ -114,21 +139,18 @@ def build_quiz_from_master(master_quiz_data):
|
|
| 114 |
|
| 115 |
if not (q_text and options and correct_idx is not None):
|
| 116 |
continue
|
| 117 |
-
|
| 118 |
try:
|
| 119 |
correct_idx_int = int(correct_idx)
|
| 120 |
except Exception:
|
| 121 |
-
# perhaps the value stored is already the correct option string
|
| 122 |
correct_idx_int = None
|
| 123 |
|
| 124 |
if correct_idx_int is None:
|
| 125 |
-
# assume 'correct' contains the correct answer string
|
| 126 |
correct_text = q.get("correct")
|
| 127 |
else:
|
| 128 |
if 0 <= correct_idx_int < len(options):
|
| 129 |
correct_text = options[correct_idx_int]
|
| 130 |
else:
|
| 131 |
-
# invalid index
|
| 132 |
correct_text = options[0]
|
| 133 |
|
| 134 |
quiz.append({"q": q_text, "options": options, "correct": correct_text})
|
|
@@ -162,14 +184,12 @@ if not st.session_state.student_info_submitted:
|
|
| 162 |
if not student_name or not student_id:
|
| 163 |
st.error("Please provide at least Name and Id.")
|
| 164 |
else:
|
| 165 |
-
# store basic info
|
| 166 |
st.session_state.student_name = student_name
|
| 167 |
st.session_state.student_class = student_class
|
| 168 |
st.session_state.student_id = student_id
|
| 169 |
st.session_state.quiz_choice = quiz_choice
|
| 170 |
st.session_state.student_info_submitted = True
|
| 171 |
|
| 172 |
-
# load master_quizzes from firebase
|
| 173 |
master = firebase_get("master_quizzes")
|
| 174 |
if master is None:
|
| 175 |
st.error("Could not load master_quizzes from Firebase.")
|
|
@@ -182,9 +202,7 @@ if not st.session_state.student_info_submitted:
|
|
| 182 |
if not quiz:
|
| 183 |
st.error("Selected quiz is empty or malformed.")
|
| 184 |
else:
|
| 185 |
-
# store quiz and start time
|
| 186 |
st.session_state.quiz = quiz
|
| 187 |
-
# initialize answers to placeholder
|
| 188 |
for i in range(len(quiz)):
|
| 189 |
st.session_state[f"q{i}"] = DEFAULT_PROMPT
|
| 190 |
st.session_state.start_time = time.time()
|
|
@@ -194,7 +212,7 @@ if not st.session_state.student_info_submitted:
|
|
| 194 |
st.stop()
|
| 195 |
|
| 196 |
# --------------------------
|
| 197 |
-
# At this point student info was submitted and quiz is loaded
|
| 198 |
# --------------------------
|
| 199 |
if not st.session_state.get("quiz_loaded"):
|
| 200 |
st.error("Quiz not loaded. Please refresh and try again.")
|
|
@@ -217,7 +235,6 @@ with st.sidebar:
|
|
| 217 |
st.write(f"Time used: {format_seconds(int(st.session_state.used_time))}")
|
| 218 |
|
| 219 |
if st.button("Reset and choose another quiz"):
|
| 220 |
-
# clear only quiz-related state so student can choose again
|
| 221 |
keys_to_remove = [k for k in list(st.session_state.keys()) if k.startswith("q") or k in ["quiz", "quiz_loaded", "start_time", "submitted", "score", "used_time"]]
|
| 222 |
for k in keys_to_remove:
|
| 223 |
del st.session_state[k]
|
|
@@ -226,8 +243,6 @@ with st.sidebar:
|
|
| 226 |
|
| 227 |
# Auto-submit when time runs out
|
| 228 |
if remaining == 0 and not st.session_state.get("submitted"):
|
| 229 |
-
# compute results and save
|
| 230 |
-
# fall through to submission logic below
|
| 231 |
pass
|
| 232 |
|
| 233 |
st.markdown("---")
|
|
@@ -236,7 +251,6 @@ st.markdown("---")
|
|
| 236 |
for i, q in enumerate(st.session_state.quiz):
|
| 237 |
st.write(f"**Question {i+1}.** {q['q']}")
|
| 238 |
display = [DEFAULT_PROMPT] + q["options"]
|
| 239 |
-
# defensive: ensure session value present and valid
|
| 240 |
if st.session_state.get(f"q{i}") not in display:
|
| 241 |
st.session_state[f"q{i}"] = DEFAULT_PROMPT
|
| 242 |
|
|
@@ -245,7 +259,7 @@ for i, q in enumerate(st.session_state.quiz):
|
|
| 245 |
|
| 246 |
st.markdown("---")
|
| 247 |
|
| 248 |
-
# Submission handling
|
| 249 |
if st.session_state.get("submitted"):
|
| 250 |
st.success(f"You scored {st.session_state.score} out of {len(st.session_state.quiz)}.")
|
| 251 |
st.write(f"Time used: {format_seconds(int(st.session_state.used_time))}")
|
|
@@ -275,44 +289,40 @@ else:
|
|
| 275 |
st.session_state.score = score
|
| 276 |
st.session_state.used_time = used_time
|
| 277 |
|
| 278 |
-
#
|
| 279 |
-
|
| 280 |
-
|
| 281 |
-
|
|
|
|
|
|
|
|
|
|
| 282 |
"Quiz": st.session_state.quiz_choice,
|
| 283 |
"Score": score,
|
| 284 |
"Time": int(used_time),
|
| 285 |
"Responses": responses,
|
| 286 |
-
"Timestamp": int(time.time()),
|
| 287 |
}
|
| 288 |
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
if
|
| 292 |
-
st.success("Saved student quiz
|
| 293 |
else:
|
| 294 |
st.error("Failed to save the quiz result to Firebase.")
|
|
|
|
| 295 |
st.experimental_rerun()
|
| 296 |
|
| 297 |
# Footer note
|
| 298 |
-
st.caption("Saved structure in Firebase under /student_quizzes/<Id> with fields: Name, Class,
|
|
|
|
| 299 |
# --------------------------
|
| 300 |
# Optional: launch a Gradio `demo` if you also created one
|
| 301 |
# --------------------------
|
| 302 |
-
# If you have a Gradio interface/Blocks assigned to the name `demo` elsewhere
|
| 303 |
-
# in the code or imported from another module, this will try to launch it.
|
| 304 |
-
# This is safe: if `demo` does not exist it will quietly skip launching.
|
| 305 |
if __name__ == "__main__":
|
| 306 |
try:
|
| 307 |
if "demo" in globals() and getattr(globals()["demo"], "launch", None):
|
| 308 |
try:
|
| 309 |
-
# Launch Gradio on 0.0.0.0:7860 (useful when deploying alongside Streamlit in special setups)
|
| 310 |
globals()["demo"].launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)
|
| 311 |
except Exception as e:
|
| 312 |
-
# Can't use st.* here safely in some environments so print instead
|
| 313 |
print(f"Gradio demo exists but failed to launch: {e}")
|
| 314 |
-
else:
|
| 315 |
-
# No demo found — nothing to do
|
| 316 |
-
pass
|
| 317 |
except Exception as e:
|
| 318 |
print(f"Error when attempting to launch Gradio demo: {e}")
|
|
|
|
| 7 |
# NOTE: page config called once at top. The title shows "Choose Quiz 1" as requested.
|
| 8 |
st.set_page_config(page_title="Lesson 1 - Part 1 - Choose Quiz 1", page_icon="🚀")
|
| 9 |
|
| 10 |
+
st.title("Quiz 1 for Lesson 1 - Part 1\nQuiz 2 for Lesson 1 - Part 2\nQuiz 3 for Lesson 2 - Part 1\nQuiz 4 for Lesson 2 - Part 2\nQuiz 5 for Lesson 2 - Part 2\nQuiz 6 for Lesson 2 - Part 2")
|
| 11 |
+
st.write("A small student quiz app that loads quizzes from Firebase and saves student results.")
|
|
|
|
| 12 |
|
| 13 |
# --------------------------
|
| 14 |
# Configuration: timer
|
|
|
|
| 28 |
FIREBASE_URL = None
|
| 29 |
FIREBASE_AUTH = None
|
| 30 |
|
| 31 |
+
# helper functions
|
| 32 |
+
|
| 33 |
def format_seconds(s):
|
| 34 |
return str(timedelta(seconds=int(s)))
|
| 35 |
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
def firebase_get(path: str):
|
| 38 |
if not FIREBASE_URL or not FIREBASE_AUTH:
|
|
|
|
| 61 |
st.error(f"Error saving to {path} in Firebase: {e}")
|
| 62 |
return False
|
| 63 |
|
| 64 |
+
|
| 65 |
+
def firebase_patch(path: str, payload):
|
| 66 |
+
"""PATCH/merge payload into the given path (creates path if not exist)."""
|
| 67 |
+
if not FIREBASE_URL or not FIREBASE_AUTH:
|
| 68 |
+
st.error("Firebase configuration missing in secrets. Please add firebase_database_url and firebase_api_key.")
|
| 69 |
+
return False
|
| 70 |
+
url = f"{FIREBASE_URL}/{path}.json?auth={FIREBASE_AUTH}"
|
| 71 |
+
try:
|
| 72 |
+
r = requests.patch(url, json=payload, timeout=10)
|
| 73 |
+
r.raise_for_status()
|
| 74 |
+
return True
|
| 75 |
+
except Exception as e:
|
| 76 |
+
st.error(f"Error patching to {path} in Firebase: {e}")
|
| 77 |
+
return False
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def firebase_post(path: str, payload):
|
| 81 |
+
"""POST to a collection path to create a new child with a unique key.
|
| 82 |
+
Returns the new child key on success, or None on failure.
|
| 83 |
+
"""
|
| 84 |
+
if not FIREBASE_URL or not FIREBASE_AUTH:
|
| 85 |
+
st.error("Firebase configuration missing in secrets. Please add firebase_database_url and firebase_api_key.")
|
| 86 |
+
return None
|
| 87 |
+
url = f"{FIREBASE_URL}/{path}.json?auth={FIREBASE_AUTH}"
|
| 88 |
+
try:
|
| 89 |
+
r = requests.post(url, json=payload, timeout=10)
|
| 90 |
+
r.raise_for_status()
|
| 91 |
+
data = r.json()
|
| 92 |
+
# Firebase returns {'name': '<new_key>'}
|
| 93 |
+
return data.get("name")
|
| 94 |
+
except Exception as e:
|
| 95 |
+
st.error(f"Error posting to {path} in Firebase: {e}")
|
| 96 |
+
return None
|
| 97 |
+
|
| 98 |
# --------------------------
|
| 99 |
+
# Quiz builder
|
| 100 |
# --------------------------
|
| 101 |
|
| 102 |
def build_quiz_from_master(master_quiz_data):
|
| 103 |
"""Expect master_quiz_data to have a 'questions' field which may be a list or dict of question objects.
|
| 104 |
+
Each question object expected fields: 'question' (string), 'options' (list of 4), 'correct' (index 0..3 or correct string)
|
| 105 |
+
Returns list of dicts: { 'q':..., 'options':[...], 'correct': <correct_option_string> }
|
| 106 |
"""
|
| 107 |
if master_quiz_data is None:
|
| 108 |
return None
|
|
|
|
| 111 |
if isinstance(master_quiz_data, dict) and "questions" in master_quiz_data:
|
| 112 |
questions_raw = master_quiz_data["questions"]
|
| 113 |
else:
|
|
|
|
| 114 |
questions_raw = master_quiz_data
|
| 115 |
|
|
|
|
| 116 |
qs = []
|
| 117 |
if isinstance(questions_raw, dict):
|
|
|
|
|
|
|
| 118 |
try:
|
| 119 |
items = sorted(questions_raw.items(), key=lambda kv: int(kv[0]))
|
| 120 |
except Exception:
|
|
|
|
| 130 |
q_text = q.get("question") if isinstance(q, dict) else None
|
| 131 |
options = q.get("options") if isinstance(q, dict) else None
|
| 132 |
correct_idx = q.get("correct") if isinstance(q, dict) else None
|
|
|
|
| 133 |
if isinstance(options, dict):
|
|
|
|
| 134 |
try:
|
| 135 |
items = sorted(options.items(), key=lambda kv: int(kv[0]))
|
| 136 |
options = [it[1] for it in items]
|
|
|
|
| 139 |
|
| 140 |
if not (q_text and options and correct_idx is not None):
|
| 141 |
continue
|
| 142 |
+
|
| 143 |
try:
|
| 144 |
correct_idx_int = int(correct_idx)
|
| 145 |
except Exception:
|
|
|
|
| 146 |
correct_idx_int = None
|
| 147 |
|
| 148 |
if correct_idx_int is None:
|
|
|
|
| 149 |
correct_text = q.get("correct")
|
| 150 |
else:
|
| 151 |
if 0 <= correct_idx_int < len(options):
|
| 152 |
correct_text = options[correct_idx_int]
|
| 153 |
else:
|
|
|
|
| 154 |
correct_text = options[0]
|
| 155 |
|
| 156 |
quiz.append({"q": q_text, "options": options, "correct": correct_text})
|
|
|
|
| 184 |
if not student_name or not student_id:
|
| 185 |
st.error("Please provide at least Name and Id.")
|
| 186 |
else:
|
|
|
|
| 187 |
st.session_state.student_name = student_name
|
| 188 |
st.session_state.student_class = student_class
|
| 189 |
st.session_state.student_id = student_id
|
| 190 |
st.session_state.quiz_choice = quiz_choice
|
| 191 |
st.session_state.student_info_submitted = True
|
| 192 |
|
|
|
|
| 193 |
master = firebase_get("master_quizzes")
|
| 194 |
if master is None:
|
| 195 |
st.error("Could not load master_quizzes from Firebase.")
|
|
|
|
| 202 |
if not quiz:
|
| 203 |
st.error("Selected quiz is empty or malformed.")
|
| 204 |
else:
|
|
|
|
| 205 |
st.session_state.quiz = quiz
|
|
|
|
| 206 |
for i in range(len(quiz)):
|
| 207 |
st.session_state[f"q{i}"] = DEFAULT_PROMPT
|
| 208 |
st.session_state.start_time = time.time()
|
|
|
|
| 212 |
st.stop()
|
| 213 |
|
| 214 |
# --------------------------
|
| 215 |
+
# At this point student info was submitted and quiz is loaded
|
| 216 |
# --------------------------
|
| 217 |
if not st.session_state.get("quiz_loaded"):
|
| 218 |
st.error("Quiz not loaded. Please refresh and try again.")
|
|
|
|
| 235 |
st.write(f"Time used: {format_seconds(int(st.session_state.used_time))}")
|
| 236 |
|
| 237 |
if st.button("Reset and choose another quiz"):
|
|
|
|
| 238 |
keys_to_remove = [k for k in list(st.session_state.keys()) if k.startswith("q") or k in ["quiz", "quiz_loaded", "start_time", "submitted", "score", "used_time"]]
|
| 239 |
for k in keys_to_remove:
|
| 240 |
del st.session_state[k]
|
|
|
|
| 243 |
|
| 244 |
# Auto-submit when time runs out
|
| 245 |
if remaining == 0 and not st.session_state.get("submitted"):
|
|
|
|
|
|
|
| 246 |
pass
|
| 247 |
|
| 248 |
st.markdown("---")
|
|
|
|
| 251 |
for i, q in enumerate(st.session_state.quiz):
|
| 252 |
st.write(f"**Question {i+1}.** {q['q']}")
|
| 253 |
display = [DEFAULT_PROMPT] + q["options"]
|
|
|
|
| 254 |
if st.session_state.get(f"q{i}") not in display:
|
| 255 |
st.session_state[f"q{i}"] = DEFAULT_PROMPT
|
| 256 |
|
|
|
|
| 259 |
|
| 260 |
st.markdown("---")
|
| 261 |
|
| 262 |
+
# Submission handling — compute score and STORE without overwriting previous quizzes
|
| 263 |
if st.session_state.get("submitted"):
|
| 264 |
st.success(f"You scored {st.session_state.score} out of {len(st.session_state.quiz)}.")
|
| 265 |
st.write(f"Time used: {format_seconds(int(st.session_state.used_time))}")
|
|
|
|
| 289 |
st.session_state.score = score
|
| 290 |
st.session_state.used_time = used_time
|
| 291 |
|
| 292 |
+
# Ensure student-level metadata (Name, Class) exist/updated without overwriting attempts
|
| 293 |
+
student_id = st.session_state.student_id
|
| 294 |
+
student_meta = {"Name": st.session_state.student_name, "Class": st.session_state.student_class, "Id": student_id}
|
| 295 |
+
patched = firebase_patch(f"student_quizzes/{student_id}", student_meta)
|
| 296 |
+
|
| 297 |
+
# Prepare payload for a single quiz attempt (no Timestamp as requested)
|
| 298 |
+
attempt_payload = {
|
| 299 |
"Quiz": st.session_state.quiz_choice,
|
| 300 |
"Score": score,
|
| 301 |
"Time": int(used_time),
|
| 302 |
"Responses": responses,
|
|
|
|
| 303 |
}
|
| 304 |
|
| 305 |
+
# POST the attempt under /student_quizzes/<student_id>/quizzes to avoid overwriting
|
| 306 |
+
new_key = firebase_post(f"student_quizzes/{student_id}/quizzes", attempt_payload)
|
| 307 |
+
if new_key:
|
| 308 |
+
st.success(f"Saved student quiz attempt under student_quizzes/{student_id}/quizzes/{new_key}")
|
| 309 |
else:
|
| 310 |
st.error("Failed to save the quiz result to Firebase.")
|
| 311 |
+
|
| 312 |
st.experimental_rerun()
|
| 313 |
|
| 314 |
# Footer note
|
| 315 |
+
st.caption("Saved structure in Firebase under /student_quizzes/<Id> with fields: Name, Class, and a child 'quizzes' containing attempts with unique keys.")
|
| 316 |
+
|
| 317 |
# --------------------------
|
| 318 |
# Optional: launch a Gradio `demo` if you also created one
|
| 319 |
# --------------------------
|
|
|
|
|
|
|
|
|
|
| 320 |
if __name__ == "__main__":
|
| 321 |
try:
|
| 322 |
if "demo" in globals() and getattr(globals()["demo"], "launch", None):
|
| 323 |
try:
|
|
|
|
| 324 |
globals()["demo"].launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False)
|
| 325 |
except Exception as e:
|
|
|
|
| 326 |
print(f"Gradio demo exists but failed to launch: {e}")
|
|
|
|
|
|
|
|
|
|
| 327 |
except Exception as e:
|
| 328 |
print(f"Error when attempting to launch Gradio demo: {e}")
|