Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,793 +1,884 @@
|
|
| 1 |
-
"""
|
| 2 |
-
ADAPTIVE AUDIO LISTENING COMPREHENSION SYSTEM
|
| 3 |
-
=============================================
|
| 4 |
-
|
| 5 |
-
Fixes in this version
|
| 6 |
-
---------------------
|
| 7 |
-
1. Google Sheets saves directly by spreadsheet ID + sheet name "Scores"
|
| 8 |
-
Columns match exactly: Date | Name | Classs | Result | Full Marks | Percentage | Star | Level
|
| 9 |
-
2. Transcript mode radio buttons are always visible and functional
|
| 10 |
-
3. Transcript appears AS SOON as audio starts playing (not after it ends)
|
| 11 |
-
and disappears after TRANSCRIPT_SHOW_SECS seconds (default 3)
|
| 12 |
-
4. Bonus star for 100% score, average star shown and logged
|
| 13 |
-
|
| 14 |
-
Expected File Structure
|
| 15 |
-
-----------------------
|
| 16 |
-
project/
|
| 17 |
-
βββ app.py
|
| 18 |
-
βββ pssg1.txt
|
| 19 |
-
βββ qstn1.txt
|
| 20 |
-
βββ audio_cache/
|
| 21 |
-
|
| 22 |
-
Setup
|
| 23 |
-
-----
|
| 24 |
-
pip install gradio gtts openai gspread oauth2client
|
| 25 |
-
|
| 26 |
-
Environment variables:
|
| 27 |
-
DEEPSEEK_API_KEY your DeepSeek key
|
| 28 |
-
gcp_service_account paste full service_account.json content as secret
|
| 29 |
-
"""
|
| 30 |
-
|
| 31 |
import os
|
| 32 |
import re
|
| 33 |
import json
|
| 34 |
-
import time
|
| 35 |
import datetime
|
|
|
|
| 36 |
import gradio as gr
|
| 37 |
-
|
|
|
|
| 38 |
from openai import OpenAI
|
| 39 |
|
| 40 |
-
|
| 41 |
-
# =========================================================
|
| 42 |
# CONFIGURATION
|
| 43 |
-
# =====================================================
|
| 44 |
|
| 45 |
-
BASE_DIR = os.
|
| 46 |
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
TRANSCRIPT_SHOW_SECS = 3 # seconds transcript stays visible
|
| 50 |
|
| 51 |
THRESHOLD_STAR = 4
|
| 52 |
LOW_STAR_LIMIT = 2
|
|
|
|
|
|
|
| 53 |
|
| 54 |
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
|
| 55 |
-
DEEPSEEK_BASE_URL = "https://api.deepseek.com"
|
| 56 |
-
DEEPSEEK_MODEL = "deepseek-chat"
|
| 57 |
-
|
| 58 |
-
# Google Sheets secret: gcp_service_account (full JSON content)
|
| 59 |
-
# Set this in HuggingFace Space β Settings β Repository secrets
|
| 60 |
|
| 61 |
-
|
| 62 |
-
# =========================================================
|
| 63 |
# LLM CLIENT
|
| 64 |
-
# =====================================================
|
| 65 |
|
| 66 |
-
def
|
| 67 |
if not DEEPSEEK_API_KEY:
|
| 68 |
return None
|
| 69 |
return OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
# =====================================================
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 96 |
)
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
|
|
|
|
|
|
| 120 |
]
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 131 |
# FILE LOADING
|
| 132 |
-
# =====================================================
|
| 133 |
|
| 134 |
def load_passages_and_questions():
|
| 135 |
-
passages
|
| 136 |
-
questions = {}
|
| 137 |
for fname in os.listdir(BASE_DIR):
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
if
|
| 141 |
-
idx = int(
|
| 142 |
with open(os.path.join(BASE_DIR, fname), encoding="utf-8") as f:
|
| 143 |
passages[idx] = f.read().strip()
|
| 144 |
-
if
|
| 145 |
-
idx = int(
|
| 146 |
with open(os.path.join(BASE_DIR, fname), encoding="utf-8") as f:
|
| 147 |
-
questions[idx] = [
|
| 148 |
return passages, questions
|
| 149 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
|
| 151 |
-
# =====================================================
|
| 152 |
-
#
|
| 153 |
-
# =====================================================
|
| 154 |
-
|
| 155 |
-
def speed_bucket(speed):
|
| 156 |
-
return "slow" if speed < 0.85 else "normal"
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
def get_audio_path(text, identifier, speed):
|
| 160 |
-
cache_dir = os.path.join(BASE_DIR, "audio_cache")
|
| 161 |
-
os.makedirs(cache_dir, exist_ok=True)
|
| 162 |
-
bucket = speed_bucket(speed)
|
| 163 |
-
filename = os.path.join(cache_dir, f"{identifier}_{bucket}.mp3")
|
| 164 |
-
if not os.path.exists(filename):
|
| 165 |
-
print(f"[Audio] Generating {filename}")
|
| 166 |
-
tts = gTTS(text, slow=(bucket == "slow"))
|
| 167 |
-
tts.save(filename)
|
| 168 |
-
return os.path.abspath(filename)
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
# =========================================================
|
| 172 |
-
# LEVEL / STARS
|
| 173 |
-
# =========================================================
|
| 174 |
|
| 175 |
def passages_for_level(level):
|
| 176 |
-
return
|
| 177 |
-
|
| 178 |
|
| 179 |
-
def
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
Examples (3 questions):
|
| 184 |
-
0/3 β 0 stars
|
| 185 |
-
1/3 β 2 stars
|
| 186 |
-
2/3 β 3 stars
|
| 187 |
-
3/3 β 5 stars (+ possible bonus star for 100%)
|
| 188 |
-
|
| 189 |
-
Examples (6 questions):
|
| 190 |
-
0/6 β 0 stars
|
| 191 |
-
1/6 β 1 star
|
| 192 |
-
2/6 β 2 stars
|
| 193 |
-
3/6 β 3 stars
|
| 194 |
-
4/6 β 4 stars
|
| 195 |
-
5/6 β 4 stars
|
| 196 |
-
6/6 β 5 stars
|
| 197 |
-
"""
|
| 198 |
-
if total <= 0 or correct <= 0:
|
| 199 |
-
return 0
|
| 200 |
-
if correct >= total:
|
| 201 |
-
return 5
|
| 202 |
-
return max(1, round(correct / total * 5))
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
def raw_stars_from_percent(p):
|
| 206 |
-
"""Kept for fallback use only."""
|
| 207 |
-
if p >= 90: return 5
|
| 208 |
-
if p >= 80: return 4
|
| 209 |
-
if p >= 70: return 3
|
| 210 |
-
if p >= 60: return 2
|
| 211 |
-
if p >= 50: return 1
|
| 212 |
-
return 0
|
| 213 |
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
if
|
| 217 |
-
|
| 218 |
-
if stars <= LOW_STAR_LIMIT:
|
| 219 |
-
return max(0, current - 1)
|
| 220 |
return current
|
| 221 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
|
| 223 |
-
def
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 227 |
|
| 228 |
-
# =====================================================
|
| 229 |
-
#
|
| 230 |
-
# =====================================================
|
|
|
|
| 231 |
|
| 232 |
-
def
|
| 233 |
-
|
| 234 |
-
if not
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
for i, (q, a) in enumerate(zip(questions, answers))
|
| 240 |
-
if q.strip()
|
| 241 |
-
)
|
| 242 |
-
system_prompt = (
|
| 243 |
-
"You are a strict but fair literacy teacher grading listening-comprehension answers. "
|
| 244 |
-
"Judge ONLY on meaning captured from the passage. Spelling mistakes are fine. "
|
| 245 |
-
"Partial credit allowed. "
|
| 246 |
-
"Return ONLY valid JSON: correct_count (float), total_questions (int), "
|
| 247 |
-
"percent (float 0-100), feedback (list of short strings, one per question)."
|
| 248 |
-
)
|
| 249 |
-
user_prompt = (
|
| 250 |
-
f"PASSAGE:\n{passage}\n\n"
|
| 251 |
-
f"QUESTIONS AND STUDENT ANSWERS:\n{qa_block}\n\nReturn JSON only."
|
| 252 |
)
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
model=DEEPSEEK_MODEL, temperature=0,
|
| 256 |
-
messages=[{"role": "system", "content": system_prompt},
|
| 257 |
-
{"role": "user", "content": user_prompt}],
|
| 258 |
-
)
|
| 259 |
-
raw = response.choices[0].message.content.strip()
|
| 260 |
-
raw = re.sub(r"^```[a-z]*\n?", "", raw)
|
| 261 |
-
raw = re.sub(r"\n?```$", "", raw)
|
| 262 |
-
return json.loads(raw)
|
| 263 |
-
except Exception as e:
|
| 264 |
-
print(f"[Grading error] {e}")
|
| 265 |
-
return _fallback_grade(questions, answers)
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
def _fallback_grade(questions, answers):
|
| 269 |
-
total = sum(1 for q in questions if q.strip())
|
| 270 |
-
answered = sum(1 for q, a in zip(questions, answers) if q.strip() and a.strip())
|
| 271 |
-
percent = round((answered / total * 100) if total else 0)
|
| 272 |
-
return {"correct_count": answered, "total_questions": total,
|
| 273 |
-
"percent": percent,
|
| 274 |
-
"feedback": ["(No LLM β credited if non-empty)"] * total}
|
| 275 |
-
|
| 276 |
|
| 277 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 278 |
# SESSION STATE
|
| 279 |
-
# =====================================================
|
| 280 |
|
| 281 |
def fresh_state():
|
| 282 |
return {
|
| 283 |
-
"
|
| 284 |
-
"
|
|
|
|
| 285 |
"level": 0,
|
| 286 |
-
|
| 287 |
-
"
|
| 288 |
-
"
|
| 289 |
-
"
|
| 290 |
-
"
|
| 291 |
-
"
|
| 292 |
-
"
|
| 293 |
-
|
| 294 |
-
"
|
| 295 |
-
"
|
| 296 |
-
"
|
| 297 |
-
|
| 298 |
-
"
|
| 299 |
-
"
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
"
|
| 303 |
-
|
| 304 |
-
"
|
| 305 |
-
"
|
| 306 |
-
|
|
|
|
|
|
|
| 307 |
}
|
| 308 |
|
| 309 |
-
|
| 310 |
-
# =========================================================
|
| 311 |
-
# CHUNK LOADING
|
| 312 |
-
# =========================================================
|
| 313 |
-
|
| 314 |
def load_next_chunk(state):
|
| 315 |
-
|
| 316 |
-
|
|
|
|
|
|
|
|
|
|
| 317 |
if not chunk:
|
| 318 |
return False
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
state["
|
| 325 |
-
state["
|
| 326 |
-
state["
|
| 327 |
-
state["
|
| 328 |
-
state["transcript_shown_at"] = None
|
| 329 |
-
state["transcript_hidden"] = True
|
| 330 |
-
state["awaiting_submit"] = False
|
| 331 |
-
ident = "chunk_" + "_".join(map(str, chunk))
|
| 332 |
-
state["audio_path"] = get_audio_path(passage_text, ident, state["speed"])
|
| 333 |
return True
|
| 334 |
|
| 335 |
-
|
| 336 |
-
# =========================================================
|
| 337 |
# UI HELPERS
|
| 338 |
-
# =====================================================
|
| 339 |
|
| 340 |
-
def
|
| 341 |
-
|
| 342 |
for i in range(MAX_QUESTIONS):
|
| 343 |
-
if
|
| 344 |
-
|
|
|
|
| 345 |
else:
|
| 346 |
-
|
| 347 |
-
|
|
|
|
| 348 |
|
|
|
|
|
|
|
| 349 |
|
| 350 |
-
def
|
| 351 |
-
|
| 352 |
-
for i in range(MAX_QUESTIONS):
|
| 353 |
-
out.append(gr.update(value="", visible=(visible and i < len(q_list))))
|
| 354 |
-
return out
|
| 355 |
-
|
| 356 |
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
| 358 |
<script>
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 365 |
</script>
|
| 366 |
"""
|
| 367 |
|
| 368 |
-
|
| 369 |
-
#
|
| 370 |
-
#
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
)
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
|
| 400 |
-
# ββ QUIZ PANEL βββββββββββββββββββββββββββββββββββββββββ
|
| 401 |
-
with gr.Group(visible=False) as quiz_panel:
|
| 402 |
-
|
| 403 |
-
status_md = gr.Markdown("### Level 0")
|
| 404 |
-
|
| 405 |
-
with gr.Row():
|
| 406 |
-
audio_out = gr.Audio(label="π Listen", type="filepath", autoplay=True)
|
| 407 |
-
btn_replay = gr.Button("π Replay", scale=0)
|
| 408 |
-
|
| 409 |
-
# FIX 3: transcript shown on audio play, not after stop
|
| 410 |
-
transcript_box = gr.Textbox(
|
| 411 |
-
label="π Transcript",
|
| 412 |
-
lines=8,
|
| 413 |
-
interactive=False,
|
| 414 |
-
placeholder="(transcript will appear here when audio plays)",
|
| 415 |
-
)
|
| 416 |
-
timer_html = gr.HTML("")
|
| 417 |
|
| 418 |
-
|
| 419 |
-
|
|
|
|
|
|
|
| 420 |
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
for i in range(MAX_QUESTIONS)]
|
| 424 |
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
btn_next = gr.Button("β‘ Next Passage", visible=False)
|
| 428 |
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
|
| 433 |
|
| 434 |
-
|
| 435 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 436 |
|
| 437 |
-
# ββββββββββββββββββββββββββββββββββββββββββ
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
def cb_start(name_val, grade_val, mode, spd, state):
|
| 442 |
-
if not name_val.strip():
|
| 443 |
-
return (state,
|
| 444 |
-
gr.update(), gr.update(), gr.update(),
|
| 445 |
-
"β οΈ Please enter your name.",
|
| 446 |
-
None, "", "", "",
|
| 447 |
-
*q_updates([], False), *a_updates([], False),
|
| 448 |
-
gr.update(visible=False), gr.update(visible=False),
|
| 449 |
-
gr.update(visible=False), "")
|
| 450 |
-
|
| 451 |
-
passages, questions_dict = load_passages_and_questions()
|
| 452 |
-
if not passages:
|
| 453 |
-
return (state,
|
| 454 |
-
gr.update(), gr.update(), gr.update(),
|
| 455 |
-
"β οΈ No pssgN.txt files found in the project folder.",
|
| 456 |
-
None, "", "", "",
|
| 457 |
-
*q_updates([], False), *a_updates([], False),
|
| 458 |
-
gr.update(visible=False), gr.update(visible=False),
|
| 459 |
-
gr.update(visible=False), "")
|
| 460 |
-
|
| 461 |
-
state["student_name"] = name_val.strip()
|
| 462 |
-
state["student_grade"] = grade_val.strip()
|
| 463 |
-
state["passages"] = passages
|
| 464 |
-
state["questions"] = questions_dict
|
| 465 |
-
state["indices"] = sorted(passages.keys())
|
| 466 |
-
state["speed"] = spd
|
| 467 |
-
state["transcript_mode"] = mode
|
| 468 |
-
|
| 469 |
-
ok = load_next_chunk(state)
|
| 470 |
-
if not ok:
|
| 471 |
-
return (state,
|
| 472 |
-
gr.update(visible=False), gr.update(visible=False),
|
| 473 |
-
gr.update(visible=True),
|
| 474 |
-
"", None, "", "", "No passages available.",
|
| 475 |
-
*q_updates([], False), *a_updates([], False),
|
| 476 |
-
gr.update(visible=False), gr.update(visible=False),
|
| 477 |
-
gr.update(visible=False), "")
|
| 478 |
-
|
| 479 |
-
total = len(state["indices"])
|
| 480 |
-
status_text = f"### Level {state['level']} | Passage 1 of {total}"
|
| 481 |
|
| 482 |
-
|
| 483 |
-
state,
|
| 484 |
-
gr.update(visible=False), # hide login
|
| 485 |
-
gr.update(visible=True), # show quiz
|
| 486 |
-
gr.update(visible=False), # done hidden
|
| 487 |
-
status_text,
|
| 488 |
-
state["audio_path"], # audio β triggers autoplay β cb_audio_play fires
|
| 489 |
-
"", # transcript blank until play fires
|
| 490 |
-
"", "",
|
| 491 |
-
*q_updates(state["current_questions"], False),
|
| 492 |
-
*a_updates([], False),
|
| 493 |
-
gr.update(visible=False), # submit hidden
|
| 494 |
-
gr.update(visible=False), # next hidden
|
| 495 |
-
gr.update(visible=True), # replay visible
|
| 496 |
-
"",
|
| 497 |
-
)
|
| 498 |
|
| 499 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 500 |
cb_start,
|
| 501 |
-
inputs=[
|
| 502 |
-
outputs=[
|
| 503 |
-
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
*q_labels, *a_boxes,
|
| 508 |
-
btn_submit, btn_next, btn_replay,
|
| 509 |
-
done_md,
|
| 510 |
-
],
|
| 511 |
)
|
| 512 |
|
| 513 |
-
|
| 514 |
-
#
|
| 515 |
-
#
|
| 516 |
-
|
| 517 |
-
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
timer_val = ""
|
| 536 |
-
else: # none
|
| 537 |
-
transcript_val = ""
|
| 538 |
-
state["transcript_shown_at"] = None
|
| 539 |
-
state["transcript_hidden"] = True
|
| 540 |
-
timer_val = ""
|
| 541 |
-
|
| 542 |
-
return state, transcript_val, timer_val
|
| 543 |
-
|
| 544 |
-
audio_out.play(
|
| 545 |
-
cb_audio_play,
|
| 546 |
-
inputs=[sess],
|
| 547 |
-
outputs=[sess, transcript_box, timer_html],
|
| 548 |
)
|
| 549 |
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
outputs=[
|
| 570 |
-
sess,
|
| 571 |
-
*q_labels, *a_boxes,
|
| 572 |
-
btn_submit, btn_next,
|
| 573 |
-
],
|
| 574 |
)
|
| 575 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 576 |
|
| 577 |
-
#
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 581 |
-
|
| 582 |
-
def cb_tick(state):
|
| 583 |
-
if state["transcript_mode"] != "disappearing":
|
| 584 |
-
return gr.update(), gr.update()
|
| 585 |
-
shown_at = state.get("transcript_shown_at")
|
| 586 |
-
if shown_at is None or state["transcript_hidden"]:
|
| 587 |
-
return gr.update(), gr.update()
|
| 588 |
-
|
| 589 |
-
elapsed = time.time() - shown_at
|
| 590 |
-
remaining = TRANSCRIPT_SHOW_SECS - elapsed
|
| 591 |
-
|
| 592 |
-
if remaining <= 0:
|
| 593 |
-
state["transcript_hidden"] = True
|
| 594 |
-
state["transcript_shown_at"] = None
|
| 595 |
-
return gr.update(value="*(Transcript hidden)*"), gr.update(value="")
|
| 596 |
-
|
| 597 |
-
timer_val = (
|
| 598 |
-
f"<p style='color:darkorange;font-weight:bold'>"
|
| 599 |
-
f"π Transcript hides in {max(1, int(remaining))}sβ¦</p>"
|
| 600 |
-
)
|
| 601 |
-
return gr.update(), gr.update(value=timer_val)
|
| 602 |
-
|
| 603 |
-
try:
|
| 604 |
-
tick = gr.Timer(value=1)
|
| 605 |
-
tick.tick(cb_tick, inputs=[sess], outputs=[transcript_box, timer_html])
|
| 606 |
-
except AttributeError:
|
| 607 |
-
pass # Gradio < 4 β transcript stays visible
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 611 |
-
# SUBMIT
|
| 612 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 613 |
-
|
| 614 |
-
def cb_submit(state, *answer_vals):
|
| 615 |
-
if not state.get("awaiting_submit"):
|
| 616 |
-
return (state,
|
| 617 |
-
"β οΈ Please listen to the full passage first.",
|
| 618 |
-
gr.update(visible=False), gr.update(visible=False),
|
| 619 |
-
gr.update(), gr.update())
|
| 620 |
-
|
| 621 |
-
answers = list(answer_vals)
|
| 622 |
questions = state["current_questions"]
|
| 623 |
-
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
|
| 644 |
-
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 693 |
cb_submit,
|
| 694 |
-
inputs=[sess
|
| 695 |
-
outputs=[sess, result_md,
|
|
|
|
|
|
|
|
|
|
| 696 |
)
|
| 697 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 698 |
|
| 699 |
-
#
|
| 700 |
-
#
|
| 701 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 702 |
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
|
| 708 |
-
|
| 709 |
-
avg = (round(sum(state["all_stars"]) / len(state["all_stars"]), 2)
|
| 710 |
-
if state["all_stars"] else 0)
|
| 711 |
-
|
| 712 |
-
# Log session summary row
|
| 713 |
-
log_to_sheets(
|
| 714 |
-
student_name = state["student_name"],
|
| 715 |
-
student_grade = state["student_grade"],
|
| 716 |
-
result = "SUMMARY",
|
| 717 |
-
full_marks = state["round_num"],
|
| 718 |
-
percent = avg * 20, # convert 0-5 avg to 0-100
|
| 719 |
-
final_stars = f"AVG={avg}",
|
| 720 |
-
level_label = f"final-level-{state['level']}",
|
| 721 |
-
)
|
| 722 |
|
| 723 |
-
|
| 724 |
-
|
| 725 |
-
|
| 726 |
-
|
| 727 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 728 |
)
|
| 729 |
return (
|
| 730 |
-
state,
|
| 731 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 736 |
)
|
| 737 |
|
| 738 |
-
|
| 739 |
-
status_text = (
|
| 740 |
-
f"### Level {state['level']} | "
|
| 741 |
-
f"Passage {state['ptr']} of {total}"
|
| 742 |
-
)
|
| 743 |
-
|
| 744 |
return (
|
| 745 |
-
state,
|
| 746 |
-
|
| 747 |
-
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
|
| 751 |
-
|
| 752 |
-
|
| 753 |
-
|
| 754 |
-
|
| 755 |
-
gr.update(visible=False),
|
| 756 |
-
gr.update(visible=True),
|
| 757 |
)
|
| 758 |
|
| 759 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 760 |
cb_next,
|
| 761 |
inputs=[sess],
|
| 762 |
-
outputs=[
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
*q_labels, *a_boxes,
|
| 768 |
-
btn_submit, btn_next, btn_replay,
|
| 769 |
-
],
|
| 770 |
)
|
| 771 |
|
| 772 |
-
|
| 773 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 774 |
-
# REPLAY
|
| 775 |
-
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 776 |
-
|
| 777 |
-
def cb_replay(state):
|
| 778 |
-
# Reset transcript timer so it shows again on replay
|
| 779 |
-
mode = state["transcript_mode"]
|
| 780 |
-
if mode == "disappearing":
|
| 781 |
-
state["transcript_shown_at"] = None # cb_audio_play will reset it
|
| 782 |
-
state["transcript_hidden"] = True
|
| 783 |
-
return state, state["audio_path"]
|
| 784 |
-
|
| 785 |
-
btn_replay.click(cb_replay, inputs=[sess], outputs=[sess, audio_out])
|
| 786 |
-
|
| 787 |
-
|
| 788 |
-
# =========================================================
|
| 789 |
-
# LAUNCH
|
| 790 |
-
# =========================================================
|
| 791 |
-
|
| 792 |
-
if __name__ == "__main__":
|
| 793 |
-
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import re
|
| 3 |
import json
|
|
|
|
| 4 |
import datetime
|
| 5 |
+
import random
|
| 6 |
import gradio as gr
|
| 7 |
+
import gspread
|
| 8 |
+
from google.oauth2.service_account import Credentials
|
| 9 |
from openai import OpenAI
|
| 10 |
|
| 11 |
+
# =====================================================
|
|
|
|
| 12 |
# CONFIGURATION
|
| 13 |
+
# =====================================================
|
| 14 |
|
| 15 |
+
BASE_DIR = os.getcwd()
|
| 16 |
|
| 17 |
+
SPREADSHEET_ID = "18oKXXwKMWE_CfKJGljWqRAKAIsp0SK6ffmkly2GHnxk"
|
| 18 |
+
WORKSHEET_NAME = "Scores"
|
|
|
|
| 19 |
|
| 20 |
THRESHOLD_STAR = 4
|
| 21 |
LOW_STAR_LIMIT = 2
|
| 22 |
+
MAX_QUESTIONS = 6
|
| 23 |
+
BLANK_TEXT = "β Answer hidden β write it from memory above."
|
| 24 |
|
| 25 |
DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
|
| 26 |
+
DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
|
| 27 |
+
DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
+
# =====================================================
|
|
|
|
| 30 |
# LLM CLIENT
|
| 31 |
+
# =====================================================
|
| 32 |
|
| 33 |
+
def _client():
|
| 34 |
if not DEEPSEEK_API_KEY:
|
| 35 |
return None
|
| 36 |
return OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL)
|
| 37 |
|
| 38 |
+
def _strip_json(raw):
|
| 39 |
+
s = (raw or "").strip()
|
| 40 |
+
if s.startswith("```"):
|
| 41 |
+
s = s.strip("`")
|
| 42 |
+
s = re.sub(r'^json', '', s).strip()
|
| 43 |
+
return s
|
| 44 |
+
|
| 45 |
+
# =====================================================
|
| 46 |
+
# LLM CALLS
|
| 47 |
+
# =====================================================
|
| 48 |
+
|
| 49 |
+
def grade_answers(pssg, qas):
|
| 50 |
+
prompt = f"""
|
| 51 |
+
You are a precise reading comprehension grader.
|
| 52 |
+
Judge ONLY factual correctness based strictly on the passage.
|
| 53 |
+
Be tolerant of paraphrasing.
|
| 54 |
+
Return ONLY valid JSON (no markdown fences):
|
| 55 |
+
{{
|
| 56 |
+
"total_questions": <int>,
|
| 57 |
+
"correct_count": <int>,
|
| 58 |
+
"percent": <float>,
|
| 59 |
+
"details": [
|
| 60 |
+
{{
|
| 61 |
+
"question": <str>,
|
| 62 |
+
"student_answer": <str>,
|
| 63 |
+
"is_correct": <bool>,
|
| 64 |
+
"reference_answer": <str>
|
| 65 |
+
}}
|
| 66 |
+
]
|
| 67 |
+
}}
|
| 68 |
+
|
| 69 |
+
DATA:
|
| 70 |
+
{json.dumps({'passage': pssg,
|
| 71 |
+
'qa_pairs': [{'question': q, 'student_answer': a} for q, a in qas]}, indent=2)}
|
| 72 |
+
"""
|
| 73 |
+
client = _client()
|
| 74 |
+
if not client:
|
| 75 |
+
return None, "No API Key"
|
| 76 |
+
r = client.chat.completions.create(
|
| 77 |
+
model=DEEPSEEK_MODEL, temperature=0,
|
| 78 |
+
messages=[
|
| 79 |
+
{"role": "system", "content": "You are a grading engine. Return only valid JSON."},
|
| 80 |
+
{"role": "user", "content": prompt}
|
| 81 |
+
]
|
| 82 |
)
|
| 83 |
+
return json.loads(_strip_json(r.choices[0].message.content)), "DeepSeek"
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def get_grammar_corrections(details):
|
| 87 |
+
prompt = f"""
|
| 88 |
+
You are an English grammar teacher.
|
| 89 |
+
For each item rewrite the student answer in correct, natural English.
|
| 90 |
+
Return ONLY valid JSON (no markdown fences):
|
| 91 |
+
{{
|
| 92 |
+
"corrections": [
|
| 93 |
+
{{"question": <str>, "original": <str>, "corrected": <str>}}
|
| 94 |
+
]
|
| 95 |
+
}}
|
| 96 |
+
|
| 97 |
+
DATA:
|
| 98 |
+
{json.dumps(details, indent=2)}
|
| 99 |
+
"""
|
| 100 |
+
client = _client()
|
| 101 |
+
if not client:
|
| 102 |
+
return []
|
| 103 |
+
r = client.chat.completions.create(
|
| 104 |
+
model=DEEPSEEK_MODEL, temperature=0,
|
| 105 |
+
messages=[
|
| 106 |
+
{"role": "system", "content": "Grammar correction engine. Return only valid JSON."},
|
| 107 |
+
{"role": "user", "content": prompt}
|
| 108 |
]
|
| 109 |
+
)
|
| 110 |
+
return json.loads(_strip_json(r.choices[0].message.content)).get("corrections", [])
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def grade_grammar_bonus(bonus_data, max_score_per_q):
|
| 114 |
+
prompt = f"""
|
| 115 |
+
You are an English grammar teacher grading a student's attempt to reproduce a corrected sentence.
|
| 116 |
+
Award bonus_score from 0 to {max_score_per_q} only (integer).
|
| 117 |
+
{max_score_per_q} = perfect: grammatically correct and same meaning
|
| 118 |
+
{max(1, max_score_per_q - 1) if max_score_per_q > 1 else 0} = mostly correct, minor errors
|
| 119 |
+
0 = mostly wrong or blank
|
| 120 |
+
|
| 121 |
+
Return ONLY valid JSON (no markdown fences):
|
| 122 |
+
{{
|
| 123 |
+
"bonus_results": [
|
| 124 |
+
{{
|
| 125 |
+
"question": <str>,
|
| 126 |
+
"corrected_answer": <str>,
|
| 127 |
+
"student_retry": <str>,
|
| 128 |
+
"bonus_score": <int>,
|
| 129 |
+
"feedback": <str>
|
| 130 |
+
}}
|
| 131 |
+
]
|
| 132 |
+
}}
|
| 133 |
+
|
| 134 |
+
DATA:
|
| 135 |
+
{json.dumps(bonus_data, indent=2)}
|
| 136 |
+
"""
|
| 137 |
+
client = _client()
|
| 138 |
+
if not client:
|
| 139 |
+
return []
|
| 140 |
+
r = client.chat.completions.create(
|
| 141 |
+
model=DEEPSEEK_MODEL, temperature=0,
|
| 142 |
+
messages=[
|
| 143 |
+
{"role": "system", "content": "Bonus grading engine. Return only valid JSON."},
|
| 144 |
+
{"role": "user", "content": prompt}
|
| 145 |
+
]
|
| 146 |
+
)
|
| 147 |
+
return json.loads(_strip_json(r.choices[0].message.content)).get("bonus_results", [])
|
| 148 |
+
|
| 149 |
+
# =====================================================
|
| 150 |
# FILE LOADING
|
| 151 |
+
# =====================================================
|
| 152 |
|
| 153 |
def load_passages_and_questions():
|
| 154 |
+
passages, questions = {}, {}
|
|
|
|
| 155 |
for fname in os.listdir(BASE_DIR):
|
| 156 |
+
pm = re.match(r'pssg(\d+)\.txt$', fname)
|
| 157 |
+
qm = re.match(r'qstn(\d+)\.txt$', fname)
|
| 158 |
+
if pm:
|
| 159 |
+
idx = int(pm.group(1))
|
| 160 |
with open(os.path.join(BASE_DIR, fname), encoding="utf-8") as f:
|
| 161 |
passages[idx] = f.read().strip()
|
| 162 |
+
if qm:
|
| 163 |
+
idx = int(qm.group(1))
|
| 164 |
with open(os.path.join(BASE_DIR, fname), encoding="utf-8") as f:
|
| 165 |
+
questions[idx] = [ln.strip() for ln in f if ln.strip()]
|
| 166 |
return passages, questions
|
| 167 |
|
| 168 |
+
def load_previous_story():
|
| 169 |
+
path = os.path.join(BASE_DIR, "previous.txt")
|
| 170 |
+
if os.path.exists(path):
|
| 171 |
+
with open(path, encoding="utf-8") as f:
|
| 172 |
+
return f.read().strip()
|
| 173 |
+
return "No previous story available."
|
| 174 |
|
| 175 |
+
# =====================================================
|
| 176 |
+
# LEVEL / CHUNK LOGIC
|
| 177 |
+
# =====================================================
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
def passages_for_level(level):
|
| 180 |
+
return max(1, level + 3)
|
|
|
|
| 181 |
|
| 182 |
+
def clamp_level(level, total_passages):
|
| 183 |
+
max_level = total_passages - 3
|
| 184 |
+
return max(-2, min(level, max_level))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
|
| 186 |
+
def compute_next_level(current, star):
|
| 187 |
+
if star is None: return 0
|
| 188 |
+
if star >= THRESHOLD_STAR: return current + 1
|
| 189 |
+
if star <= LOW_STAR_LIMIT: return current - 1
|
|
|
|
|
|
|
| 190 |
return current
|
| 191 |
|
| 192 |
+
def stars_from_percent(pct):
|
| 193 |
+
if pct >= 90: return 5
|
| 194 |
+
if pct >= 80: return 4
|
| 195 |
+
if pct >= 70: return 3
|
| 196 |
+
if pct >= 60: return 2
|
| 197 |
+
if pct >= 50: return 1
|
| 198 |
+
return 0
|
| 199 |
|
| 200 |
+
def pick_questions(questions_dict, indices, level):
|
| 201 |
+
q_list = []
|
| 202 |
+
for i in indices:
|
| 203 |
+
q_list.extend(questions_dict.get(i, []))
|
| 204 |
+
if level >= 1 and len(q_list) > 4:
|
| 205 |
+
chosen = sorted(random.sample(range(len(q_list)), 4))
|
| 206 |
+
q_list = [q_list[i] for i in chosen]
|
| 207 |
+
return q_list
|
| 208 |
|
| 209 |
+
# =====================================================
|
| 210 |
+
# GOOGLE SHEET
|
| 211 |
+
# =====================================================
|
| 212 |
+
# Columns: A Timestamp | B Name | C Grade | D Correct | E Total | F Percent% | G Stars | H Label
|
| 213 |
|
| 214 |
+
def get_sheet():
|
| 215 |
+
svc_json = os.environ.get("gcp_service_account")
|
| 216 |
+
if not svc_json:
|
| 217 |
+
raise RuntimeError("gcp_service_account env var not set")
|
| 218 |
+
creds = Credentials.from_service_account_info(
|
| 219 |
+
json.loads(svc_json),
|
| 220 |
+
scopes=["https://www.googleapis.com/auth/spreadsheets"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 221 |
)
|
| 222 |
+
gc = gspread.authorize(creds)
|
| 223 |
+
return gc.open_by_key(SPREADSHEET_ID).worksheet(WORKSHEET_NAME)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
|
| 225 |
+
def get_last_record(name, grade):
|
| 226 |
+
"""
|
| 227 |
+
Reads the sheet newest-first to find this student's last result.
|
| 228 |
+
Returns (level, stars) used to compute their starting level today.
|
| 229 |
+
New students return (0, None) -> level 0.
|
| 230 |
+
"""
|
| 231 |
+
try:
|
| 232 |
+
rows = get_sheet().get_all_values()
|
| 233 |
+
for row in reversed(rows[1:]): # newest first
|
| 234 |
+
if len(row) < 7:
|
| 235 |
+
continue
|
| 236 |
+
if (row[1].strip().lower() != name.strip().lower() or
|
| 237 |
+
row[2].strip().lower() != grade.strip().lower()):
|
| 238 |
+
continue
|
| 239 |
+
# Col G (index 6) = stars
|
| 240 |
+
try:
|
| 241 |
+
star = float(str(row[6]).replace(',', '.'))
|
| 242 |
+
except (ValueError, IndexError):
|
| 243 |
+
star = None
|
| 244 |
+
# Col H (index 7) = "Comprehension--Reading-level N"
|
| 245 |
+
level = 0
|
| 246 |
+
if len(row) > 7:
|
| 247 |
+
m = re.search(r'level\s*(-?\d+)', row[7], re.I)
|
| 248 |
+
if m:
|
| 249 |
+
level = int(m.group(1))
|
| 250 |
+
return level, star
|
| 251 |
+
return 0, None # new student
|
| 252 |
+
except Exception:
|
| 253 |
+
return 0, None # sheet error β safe default
|
| 254 |
+
|
| 255 |
+
def save_final_result(name, grade, level, correct_total, q_total, avg_percent, final_stars):
|
| 256 |
+
"""Save ONE summary row at end of entire session."""
|
| 257 |
+
row = [
|
| 258 |
+
datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S"), # A
|
| 259 |
+
name, # B
|
| 260 |
+
grade, # C
|
| 261 |
+
int(correct_total), # D
|
| 262 |
+
int(q_total), # E
|
| 263 |
+
f"{avg_percent:.1f}%", # F
|
| 264 |
+
round(float(final_stars), 2), # G
|
| 265 |
+
f"Comprehension--Reading-level {level}" # H
|
| 266 |
+
]
|
| 267 |
+
sheet = get_sheet()
|
| 268 |
+
sheet.append_row(row, value_input_option="USER_ENTERED")
|
| 269 |
+
|
| 270 |
+
# =====================================================
|
| 271 |
# SESSION STATE
|
| 272 |
+
# =====================================================
|
| 273 |
|
| 274 |
def fresh_state():
|
| 275 |
return {
|
| 276 |
+
"name": "", "grade": "",
|
| 277 |
+
"all_passages": {}, "all_questions": {},
|
| 278 |
+
"sorted_indices": [], "next_index": 0,
|
| 279 |
"level": 0,
|
| 280 |
+
# per-chunk accumulators (filled after each grammar bonus round)
|
| 281 |
+
"chunk_earned_stars": [],
|
| 282 |
+
"chunk_bonus_stars": [],
|
| 283 |
+
"chunk_corrects": [],
|
| 284 |
+
"chunk_totals": [],
|
| 285 |
+
"chunk_percents": [],
|
| 286 |
+
"phase": "idle",
|
| 287 |
+
# current chunk
|
| 288 |
+
"current_passage": "",
|
| 289 |
+
"current_questions": [],
|
| 290 |
+
"current_indices": [],
|
| 291 |
+
"current_correct": 0,
|
| 292 |
+
"current_total": 0,
|
| 293 |
+
"current_percent": 0.0,
|
| 294 |
+
"current_earned_stars": 0,
|
| 295 |
+
# grammar bonus
|
| 296 |
+
"corrections": [],
|
| 297 |
+
"result_text": "",
|
| 298 |
+
"bonus_mode": None, # "disappearing" | "static"
|
| 299 |
+
"mode_locked": False,
|
| 300 |
+
# timer
|
| 301 |
+
"timer_elapsed": 0,
|
| 302 |
+
"blanked_count": 0,
|
| 303 |
}
|
| 304 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 305 |
def load_next_chunk(state):
|
| 306 |
+
indices = state["sorted_indices"]
|
| 307 |
+
ptr = state["next_index"]
|
| 308 |
+
level = state["level"]
|
| 309 |
+
size = passages_for_level(level)
|
| 310 |
+
chunk = indices[ptr: ptr + size]
|
| 311 |
if not chunk:
|
| 312 |
return False
|
| 313 |
+
state["current_indices"] = chunk
|
| 314 |
+
state["current_passage"] = "\n\n".join(
|
| 315 |
+
state["all_passages"][i] for i in chunk if i in state["all_passages"]
|
| 316 |
+
)
|
| 317 |
+
state["current_questions"] = pick_questions(state["all_questions"], chunk, level)
|
| 318 |
+
state["next_index"] = ptr + size
|
| 319 |
+
state["phase"] = "answering"
|
| 320 |
+
state["bonus_mode"] = None
|
| 321 |
+
state["mode_locked"] = False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 322 |
return True
|
| 323 |
|
| 324 |
+
# =====================================================
|
|
|
|
| 325 |
# UI HELPERS
|
| 326 |
+
# =====================================================
|
| 327 |
|
| 328 |
+
def qa_ui(questions, interactive=True):
|
| 329 |
+
updates = []
|
| 330 |
for i in range(MAX_QUESTIONS):
|
| 331 |
+
if i < len(questions):
|
| 332 |
+
updates.append(gr.update(value=f"**Q{i+1}:** {questions[i]}", visible=True))
|
| 333 |
+
updates.append(gr.update(value="", visible=True, interactive=interactive))
|
| 334 |
else:
|
| 335 |
+
updates.append(gr.update(visible=False))
|
| 336 |
+
updates.append(gr.update(value="", visible=False))
|
| 337 |
+
return updates
|
| 338 |
|
| 339 |
+
def hide_pairs(n):
|
| 340 |
+
return [gr.update(visible=False) for _ in range(n * 2)]
|
| 341 |
|
| 342 |
+
def hide_n(n):
|
| 343 |
+
return [gr.update(visible=False) for _ in range(n)]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 344 |
|
| 345 |
+
# JS injected once at page load.
|
| 346 |
+
# Blocks copy / cut / paste / right-click / drag on ALL textareas AND
|
| 347 |
+
# the whole document (covers passage text selected with mouse too).
|
| 348 |
+
COPY_BLOCK_JS = """
|
| 349 |
<script>
|
| 350 |
+
(function() {
|
| 351 |
+
var BLOCK = ['copy','cut','paste','contextmenu','dragstart','drop','selectstart'];
|
| 352 |
+
|
| 353 |
+
/* 1. Block on the document level β covers mouse-selected text anywhere */
|
| 354 |
+
BLOCK.forEach(function(ev) {
|
| 355 |
+
document.addEventListener(ev, function(e) {
|
| 356 |
+
e.preventDefault();
|
| 357 |
+
e.stopPropagation();
|
| 358 |
+
return false;
|
| 359 |
+
}, true); /* capture phase so it fires before any element handler */
|
| 360 |
+
});
|
| 361 |
+
|
| 362 |
+
/* 2. Also set -webkit-user-select on every textarea so it looks unselectable */
|
| 363 |
+
function lockAllTextareas() {
|
| 364 |
+
document.querySelectorAll('textarea, input[type="text"]').forEach(function(el) {
|
| 365 |
+
if (el.dataset.copyBlocked) return;
|
| 366 |
+
el.dataset.copyBlocked = '1';
|
| 367 |
+
el.style.webkitUserSelect = 'none';
|
| 368 |
+
el.style.userSelect = 'none';
|
| 369 |
+
BLOCK.forEach(function(ev) {
|
| 370 |
+
el.addEventListener(ev, function(e) {
|
| 371 |
+
e.preventDefault(); e.stopPropagation(); return false;
|
| 372 |
+
}, true);
|
| 373 |
+
});
|
| 374 |
+
});
|
| 375 |
+
}
|
| 376 |
+
|
| 377 |
+
lockAllTextareas();
|
| 378 |
+
setInterval(lockAllTextareas, 800); /* catch Gradio's async-rendered elements */
|
| 379 |
+
})();
|
| 380 |
</script>
|
| 381 |
"""
|
| 382 |
|
| 383 |
+
# =====================================================
|
| 384 |
+
# GRADIO APP
|
| 385 |
+
# =====================================================
|
| 386 |
+
|
| 387 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 388 |
+
|
| 389 |
+
gr.Markdown("# π Adaptive Reading Comprehension")
|
| 390 |
+
|
| 391 |
+
# Inject copy-block JS once at page load
|
| 392 |
+
gr.HTML(COPY_BLOCK_JS)
|
| 393 |
+
|
| 394 |
+
# ββ Login ββββββββββββββββββββββββββββββββββββββββββ
|
| 395 |
+
with gr.Row():
|
| 396 |
+
name_tb = gr.Textbox(label="Student Name", scale=2)
|
| 397 |
+
grade_tb = gr.Textbox(label="Class / Grade", scale=1)
|
| 398 |
+
with gr.Row():
|
| 399 |
+
view_prev_btn = gr.Button("π View Previous Parts")
|
| 400 |
+
proceed_btn = gr.Button("βΆ Proceed to This Week")
|
| 401 |
+
|
| 402 |
+
prev_box = gr.Textbox(label="Previous Story", lines=12,
|
| 403 |
+
visible=False, interactive=False)
|
| 404 |
+
start_btn = gr.Button("π Start Session", visible=False)
|
| 405 |
+
|
| 406 |
+
# ββ Reading ββββββββββββββββββββββββββββββββββββββββ
|
| 407 |
+
status_md = gr.Markdown(visible=False)
|
| 408 |
+
passage_bx = gr.Textbox(label="Passage", lines=15,
|
| 409 |
+
interactive=False, visible=False)
|
| 410 |
+
|
| 411 |
+
# ββ Grammar mode selector ββββββββββββββββββββββββββ
|
| 412 |
+
mode_row = gr.Row(visible=False)
|
| 413 |
+
with mode_row:
|
| 414 |
+
gr.Markdown(
|
| 415 |
+
"### π― Choose Grammar Bonus Mode β select before you start answering\n\n"
|
| 416 |
+
"| Mode | Bonus Stars | What happens |\n|---|---|---|\n"
|
| 417 |
+
"| β
Disappearing | up to **+3** β | Corrected answers vanish after a few seconds |\n"
|
| 418 |
+
"| β
Stays visible | up to **+1** β | Corrected answers stay on screen |"
|
| 419 |
)
|
| 420 |
+
mode_check_row = gr.Row(visible=False)
|
| 421 |
+
with mode_check_row:
|
| 422 |
+
disappearing_cb = gr.Checkbox(label="Disappearing answers (+3 bonus stars)", value=False)
|
| 423 |
+
static_cb = gr.Checkbox(label="Answers stay visible (+1 bonus star)", value=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
+
# Q&A slots β non-interactive until mode chosen
|
| 426 |
+
q_boxes = [gr.Markdown(visible=False) for _ in range(MAX_QUESTIONS)]
|
| 427 |
+
a_boxes = [gr.Textbox(label=f"Your Answer {i+1}", visible=False, interactive=False)
|
| 428 |
+
for i in range(MAX_QUESTIONS)]
|
| 429 |
|
| 430 |
+
grading_msg = gr.Markdown(visible=False)
|
| 431 |
+
submit_btn = gr.Button("β
Submit Answers", visible=False)
|
|
|
|
| 432 |
|
| 433 |
+
# ββ Grammar bonus ββββββββββββββββββββββββββββββββββ
|
| 434 |
+
grammar_hdr = gr.Markdown(visible=False)
|
|
|
|
| 435 |
|
| 436 |
+
corrected_boxes = [
|
| 437 |
+
gr.Textbox(label=f"βοΈ Corrected Answer {i+1}", visible=False, interactive=False)
|
| 438 |
+
for i in range(MAX_QUESTIONS)
|
| 439 |
+
]
|
| 440 |
|
| 441 |
+
blank_timer = gr.Timer(value=1, active=False)
|
| 442 |
|
| 443 |
+
gi_boxes = [gr.Markdown(visible=False) for _ in range(MAX_QUESTIONS)]
|
| 444 |
+
gr_boxes = [gr.Textbox(label=f"Grammar Retry {i+1}", visible=False)
|
| 445 |
+
for i in range(MAX_QUESTIONS)]
|
| 446 |
+
bonus_btn = gr.Button("π― Submit Grammar Retry", visible=False)
|
| 447 |
|
| 448 |
+
# ββ Results ββββββββββββββββββββββββββββββββββββββββ
|
| 449 |
+
result_md = gr.Markdown(visible=False)
|
| 450 |
+
next_btn = gr.Button("β‘ Next Passage Set", visible=False)
|
| 451 |
+
final_md = gr.Markdown(visible=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 452 |
|
| 453 |
+
sess = gr.State(fresh_state())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 454 |
|
| 455 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 456 |
+
# VIEW PREVIOUS / PROCEED
|
| 457 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 458 |
+
def cb_view_prev(_):
|
| 459 |
+
return gr.update(value=load_previous_story(), visible=True)
|
| 460 |
+
view_prev_btn.click(cb_view_prev, inputs=[prev_box], outputs=[prev_box])
|
| 461 |
+
|
| 462 |
+
def cb_proceed(_):
|
| 463 |
+
return gr.update(visible=False), gr.update(visible=True)
|
| 464 |
+
proceed_btn.click(cb_proceed, inputs=[prev_box], outputs=[prev_box, start_btn])
|
| 465 |
+
|
| 466 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 467 |
+
# START SESSION
|
| 468 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 469 |
+
def cb_start(name, grade, state):
|
| 470 |
+
passages, questions = load_passages_and_questions()
|
| 471 |
+
total = len(passages)
|
| 472 |
+
if total == 0:
|
| 473 |
+
return ([state,
|
| 474 |
+
gr.update(value="β οΈ No passage files found.", visible=True)]
|
| 475 |
+
+ [gr.update(visible=False)] * 8
|
| 476 |
+
+ hide_pairs(MAX_QUESTIONS))
|
| 477 |
+
|
| 478 |
+
last_level, last_star = get_last_record(name, grade)
|
| 479 |
+
level = clamp_level(compute_next_level(last_level, last_star), total)
|
| 480 |
+
|
| 481 |
+
state.update({
|
| 482 |
+
"name": name, "grade": grade,
|
| 483 |
+
"all_passages": passages, "all_questions": questions,
|
| 484 |
+
"sorted_indices": sorted(passages.keys()),
|
| 485 |
+
"next_index": 0, "level": level,
|
| 486 |
+
"chunk_earned_stars": [], "chunk_bonus_stars": [],
|
| 487 |
+
"chunk_corrects": [], "chunk_totals": [], "chunk_percents": [],
|
| 488 |
+
})
|
| 489 |
+
|
| 490 |
+
if not load_next_chunk(state):
|
| 491 |
+
return ([state,
|
| 492 |
+
gr.update(value="β οΈ No passages available.", visible=True)]
|
| 493 |
+
+ [gr.update(visible=False)] * 8
|
| 494 |
+
+ hide_pairs(MAX_QUESTIONS))
|
| 495 |
+
|
| 496 |
+
ci = state["current_indices"]
|
| 497 |
+
return ([state,
|
| 498 |
+
gr.update(value=f"## π Level {level} β Passages {ci[0]}β{ci[-1]}", visible=True),
|
| 499 |
+
gr.update(value=state["current_passage"], visible=True),
|
| 500 |
+
gr.update(visible=True), # mode_row
|
| 501 |
+
gr.update(visible=True), # mode_check_row
|
| 502 |
+
gr.update(value=False), # disappearing_cb
|
| 503 |
+
gr.update(value=False), # static_cb
|
| 504 |
+
gr.update(visible=False), # submit_btn
|
| 505 |
+
gr.update(visible=False), # result_md
|
| 506 |
+
gr.update(visible=False)] # next_btn
|
| 507 |
+
+ qa_ui(state["current_questions"], interactive=False))
|
| 508 |
+
|
| 509 |
+
start_btn.click(
|
| 510 |
cb_start,
|
| 511 |
+
inputs=[name_tb, grade_tb, sess],
|
| 512 |
+
outputs=([sess, status_md, passage_bx,
|
| 513 |
+
mode_row, mode_check_row,
|
| 514 |
+
disappearing_cb, static_cb,
|
| 515 |
+
submit_btn, result_md, next_btn]
|
| 516 |
+
+ [x for pair in zip(q_boxes, a_boxes) for x in pair])
|
|
|
|
|
|
|
|
|
|
|
|
|
| 517 |
)
|
| 518 |
|
| 519 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 520 |
+
# MODE CHECKBOXES β mutual exclusion, lock on select, unlock answers
|
| 521 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 522 |
+
def cb_select_disappearing(checked, state):
|
| 523 |
+
if state.get("mode_locked"):
|
| 524 |
+
return ([gr.update()] * 2 + [state, gr.update(visible=False)]
|
| 525 |
+
+ [gr.update() for _ in range(MAX_QUESTIONS)])
|
| 526 |
+
if checked:
|
| 527 |
+
state["bonus_mode"] = "disappearing"
|
| 528 |
+
state["mode_locked"] = True
|
| 529 |
+
return ([gr.update(value=True, interactive=False),
|
| 530 |
+
gr.update(value=False, interactive=False),
|
| 531 |
+
state,
|
| 532 |
+
gr.update(visible=True)]
|
| 533 |
+
+ [gr.update(interactive=True) for _ in range(MAX_QUESTIONS)])
|
| 534 |
+
return ([gr.update()] * 2 + [state, gr.update(visible=False)]
|
| 535 |
+
+ [gr.update() for _ in range(MAX_QUESTIONS)])
|
| 536 |
+
|
| 537 |
+
disappearing_cb.change(
|
| 538 |
+
cb_select_disappearing,
|
| 539 |
+
inputs=[disappearing_cb, sess],
|
| 540 |
+
outputs=[disappearing_cb, static_cb, sess, submit_btn] + a_boxes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 541 |
)
|
| 542 |
|
| 543 |
+
def cb_select_static(checked, state):
|
| 544 |
+
if state.get("mode_locked"):
|
| 545 |
+
return ([gr.update()] * 2 + [state, gr.update(visible=False)]
|
| 546 |
+
+ [gr.update() for _ in range(MAX_QUESTIONS)])
|
| 547 |
+
if checked:
|
| 548 |
+
state["bonus_mode"] = "static"
|
| 549 |
+
state["mode_locked"] = True
|
| 550 |
+
return ([gr.update(value=False, interactive=False),
|
| 551 |
+
gr.update(value=True, interactive=False),
|
| 552 |
+
state,
|
| 553 |
+
gr.update(visible=True)]
|
| 554 |
+
+ [gr.update(interactive=True) for _ in range(MAX_QUESTIONS)])
|
| 555 |
+
return ([gr.update()] * 2 + [state, gr.update(visible=False)]
|
| 556 |
+
+ [gr.update() for _ in range(MAX_QUESTIONS)])
|
| 557 |
+
|
| 558 |
+
static_cb.change(
|
| 559 |
+
cb_select_static,
|
| 560 |
+
inputs=[static_cb, sess],
|
| 561 |
+
outputs=[disappearing_cb, static_cb, sess, submit_btn] + a_boxes
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 562 |
)
|
| 563 |
|
| 564 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 565 |
+
# SUBMIT ANSWERS β step 1: show spinner
|
| 566 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 567 |
+
def cb_submit_start(state):
|
| 568 |
+
return (gr.update(visible=False),
|
| 569 |
+
gr.update(value="Ⳡ**Grading your answers⦠please wait.**", visible=True))
|
| 570 |
|
| 571 |
+
# SUBMIT ANSWERS β step 2: grade + show grammar panel
|
| 572 |
+
def cb_submit(state, *answers):
|
| 573 |
+
answers = list(answers)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 574 |
questions = state["current_questions"]
|
| 575 |
+
pssg = state["current_passage"]
|
| 576 |
+
mode = state.get("bonus_mode") or "static"
|
| 577 |
+
|
| 578 |
+
qas = [(q, answers[i] if i < len(answers) else "") for i, q in enumerate(questions)]
|
| 579 |
+
result, who = grade_answers(pssg, qas)
|
| 580 |
+
|
| 581 |
+
FAIL = ([state,
|
| 582 |
+
gr.update(value="β οΈ Grading failed β check API key.", visible=True),
|
| 583 |
+
gr.update(visible=False), gr.update(visible=False),
|
| 584 |
+
gr.update(visible=False), gr.update(visible=False),
|
| 585 |
+
gr.update(visible=False), gr.update(active=False)]
|
| 586 |
+
+ hide_n(MAX_QUESTIONS) + hide_pairs(MAX_QUESTIONS))
|
| 587 |
+
if result is None:
|
| 588 |
+
return FAIL
|
| 589 |
+
|
| 590 |
+
correct = result["correct_count"]
|
| 591 |
+
total_q = result["total_questions"]
|
| 592 |
+
percent = result["percent"]
|
| 593 |
+
stars = stars_from_percent(percent)
|
| 594 |
+
|
| 595 |
+
state["chunk_earned_stars"].append(float(stars))
|
| 596 |
+
state["chunk_corrects"].append(correct)
|
| 597 |
+
state["chunk_totals"].append(total_q)
|
| 598 |
+
state["chunk_percents"].append(percent)
|
| 599 |
+
state["current_correct"] = correct
|
| 600 |
+
state["current_total"] = total_q
|
| 601 |
+
state["current_percent"] = percent
|
| 602 |
+
state["current_earned_stars"] = stars
|
| 603 |
+
state["timer_elapsed"] = 0
|
| 604 |
+
state["blanked_count"] = 0
|
| 605 |
+
|
| 606 |
+
txt = (f"### β
Graded by {who}\n\n"
|
| 607 |
+
f"**Score:** {percent:.1f}% | **Correct:** {correct}/{total_q} | "
|
| 608 |
+
f"**Stars:** {'β'*stars} ({stars}/5)\n\n---\n")
|
| 609 |
+
for d in result["details"]:
|
| 610 |
+
sym = "β
" if d["is_correct"] else "β"
|
| 611 |
+
txt += f"\n{sym} **{d['question']}**\n- Your answer: _{d['student_answer']}_\n"
|
| 612 |
+
if not d["is_correct"]:
|
| 613 |
+
txt += f"- Correct answer: _{d['reference_answer']}_\n"
|
| 614 |
+
state["result_text"] = txt
|
| 615 |
+
|
| 616 |
+
corrections = get_grammar_corrections(result["details"])
|
| 617 |
+
state["corrections"] = corrections
|
| 618 |
+
state["phase"] = "grammar_bonus"
|
| 619 |
+
|
| 620 |
+
n = len(corrections)
|
| 621 |
+
max_bonus = 3 if mode == "disappearing" else 1
|
| 622 |
+
|
| 623 |
+
hdr = (f"## βοΈ Grammar Practice "
|
| 624 |
+
f"({'π Disappearing β up to +3 β' if mode=='disappearing' else 'π Static β up to +1 β'})\n\n"
|
| 625 |
+
+ ("Memorise each answer before it disappears, then write it from memory. "
|
| 626 |
+
if mode == "disappearing"
|
| 627 |
+
else "Read each corrected answer, then write it in your own correct English. ")
|
| 628 |
+
+ f"Max bonus per question: **+{max_bonus}**.")
|
| 629 |
+
|
| 630 |
+
corr_updates = []
|
| 631 |
+
retry_updates = []
|
| 632 |
+
for i in range(MAX_QUESTIONS):
|
| 633 |
+
if i < n:
|
| 634 |
+
c = corrections[i]
|
| 635 |
+
lbl = (f"βοΈ Corrected Answer {i+1} β³ hides in {(i+1)*5}s"
|
| 636 |
+
if mode == "disappearing"
|
| 637 |
+
else f"βοΈ Corrected Answer {i+1}")
|
| 638 |
+
corr_updates.append(gr.update(value=c["corrected"], label=lbl,
|
| 639 |
+
visible=True, interactive=False))
|
| 640 |
+
retry_updates.append(gr.update(
|
| 641 |
+
value=f"**Q{i+1}:** {c['question']}\n\nWrite the corrected sentence from memory:",
|
| 642 |
+
visible=True))
|
| 643 |
+
retry_updates.append(gr.update(value="", visible=True, interactive=True))
|
| 644 |
+
else:
|
| 645 |
+
corr_updates.append(gr.update(value="", visible=False))
|
| 646 |
+
retry_updates.append(gr.update(visible=False))
|
| 647 |
+
retry_updates.append(gr.update(value="", visible=False))
|
| 648 |
+
|
| 649 |
+
return ([state,
|
| 650 |
+
gr.update(value=txt, visible=True), # result_md
|
| 651 |
+
gr.update(visible=False), # submit_btn
|
| 652 |
+
gr.update(visible=False), # grading_msg
|
| 653 |
+
gr.update(value=hdr, visible=True), # grammar_hdr
|
| 654 |
+
gr.update(visible=True), # bonus_btn
|
| 655 |
+
gr.update(visible=False), # next_btn
|
| 656 |
+
gr.update(active=(mode == "disappearing"))] # blank_timer
|
| 657 |
+
+ corr_updates
|
| 658 |
+
+ retry_updates)
|
| 659 |
+
|
| 660 |
+
submit_btn.click(
|
| 661 |
+
cb_submit_start, inputs=[sess], outputs=[submit_btn, grading_msg]
|
| 662 |
+
).then(
|
| 663 |
cb_submit,
|
| 664 |
+
inputs=[sess] + a_boxes,
|
| 665 |
+
outputs=([sess, result_md, submit_btn, grading_msg,
|
| 666 |
+
grammar_hdr, bonus_btn, next_btn, blank_timer]
|
| 667 |
+
+ corrected_boxes
|
| 668 |
+
+ [x for pair in zip(gi_boxes, gr_boxes) for x in pair])
|
| 669 |
)
|
| 670 |
|
| 671 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 672 |
+
# TIMER TICK β blank corrected boxes one by one
|
| 673 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 674 |
+
def cb_timer_tick(state):
|
| 675 |
+
if state["phase"] != "grammar_bonus" or state.get("bonus_mode") != "disappearing":
|
| 676 |
+
return [gr.update(active=False), state] + [gr.update()] * MAX_QUESTIONS
|
| 677 |
+
|
| 678 |
+
corrections = state["corrections"]
|
| 679 |
+
n = len(corrections)
|
| 680 |
+
elapsed = state.get("timer_elapsed", 0) + 1
|
| 681 |
+
state["timer_elapsed"] = elapsed
|
| 682 |
+
blanked = state.get("blanked_count", 0)
|
| 683 |
+
|
| 684 |
+
updates = []
|
| 685 |
+
newly = blanked
|
| 686 |
+
for i in range(MAX_QUESTIONS):
|
| 687 |
+
if i < n:
|
| 688 |
+
blank_at = (i + 1) * 5
|
| 689 |
+
remaining = max(0, blank_at - elapsed)
|
| 690 |
+
if elapsed >= blank_at and i >= blanked:
|
| 691 |
+
updates.append(gr.update(value=BLANK_TEXT,
|
| 692 |
+
label=f"βοΈ Corrected Answer {i+1} [hidden]"))
|
| 693 |
+
newly = i + 1
|
| 694 |
+
elif elapsed < blank_at:
|
| 695 |
+
updates.append(gr.update(
|
| 696 |
+
label=f"βοΈ Corrected Answer {i+1} β³ hides in {remaining}s"))
|
| 697 |
+
else:
|
| 698 |
+
updates.append(gr.update())
|
| 699 |
+
else:
|
| 700 |
+
updates.append(gr.update())
|
| 701 |
+
|
| 702 |
+
state["blanked_count"] = newly
|
| 703 |
+
all_done = (elapsed >= n * 5)
|
| 704 |
+
return [gr.update(active=not all_done), state] + updates
|
| 705 |
+
|
| 706 |
+
blank_timer.tick(
|
| 707 |
+
cb_timer_tick, inputs=[sess],
|
| 708 |
+
outputs=[blank_timer, sess] + corrected_boxes
|
| 709 |
+
)
|
| 710 |
|
| 711 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 712 |
+
# SUBMIT GRAMMAR BONUS β step 1: spinner
|
| 713 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 714 |
+
def cb_bonus_start(state):
|
| 715 |
+
return (gr.update(visible=False),
|
| 716 |
+
gr.update(value="Ⳡ**Grading your grammar retry⦠please wait.**", visible=True))
|
| 717 |
+
|
| 718 |
+
# SUBMIT GRAMMAR BONUS β step 2: grade, accumulate, maybe save
|
| 719 |
+
def cb_bonus(state, *retries):
|
| 720 |
+
retries = list(retries)
|
| 721 |
+
corrections = state["corrections"]
|
| 722 |
+
mode = state.get("bonus_mode") or "static"
|
| 723 |
+
max_bonus = 3 if mode == "disappearing" else 1
|
| 724 |
+
|
| 725 |
+
bonus_data = [
|
| 726 |
+
{"question": c["question"],
|
| 727 |
+
"corrected_answer": c["corrected"],
|
| 728 |
+
"student_retry": retries[i] if i < len(retries) else ""}
|
| 729 |
+
for i, c in enumerate(corrections)
|
| 730 |
+
]
|
| 731 |
+
bonus_results = grade_grammar_bonus(bonus_data, max_score_per_q=max_bonus)
|
| 732 |
|
| 733 |
+
avg_bonus = (sum(b["bonus_score"] for b in bonus_results) / len(bonus_results)
|
| 734 |
+
if bonus_results else 0.0)
|
| 735 |
+
state["chunk_bonus_stars"].append(avg_bonus)
|
| 736 |
+
|
| 737 |
+
earned_this = state["current_earned_stars"]
|
| 738 |
+
total_this = earned_this + avg_bonus
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 739 |
|
| 740 |
+
# Adjust level for next chunk
|
| 741 |
+
state["level"] = clamp_level(
|
| 742 |
+
compute_next_level(state["level"], earned_this),
|
| 743 |
+
len(state["sorted_indices"])
|
| 744 |
+
)
|
| 745 |
+
state["phase"] = "idle"
|
| 746 |
+
state["timer_elapsed"] = 0
|
| 747 |
+
state["blanked_count"] = 0
|
| 748 |
+
|
| 749 |
+
# ββ Check if this was the LAST chunk ββββββββββββββββββββββββββββββββββ
|
| 750 |
+
# has_more is True if there are still unread passages
|
| 751 |
+
has_more = state["next_index"] < len(state["sorted_indices"])
|
| 752 |
+
|
| 753 |
+
save_msg = ""
|
| 754 |
+
if not has_more:
|
| 755 |
+
# This IS the final chunk β save now
|
| 756 |
+
n = len(state["chunk_earned_stars"])
|
| 757 |
+
ae = sum(state["chunk_earned_stars"]) / n if n else 0.0
|
| 758 |
+
ab = sum(state["chunk_bonus_stars"]) / n if n else 0.0
|
| 759 |
+
ft = ae + ab
|
| 760 |
+
|
| 761 |
+
total_correct = sum(state["chunk_corrects"])
|
| 762 |
+
total_qs = sum(state["chunk_totals"])
|
| 763 |
+
avg_pct = sum(state["chunk_percents"]) / n if n else 0.0
|
| 764 |
+
|
| 765 |
+
try:
|
| 766 |
+
save_final_result(
|
| 767 |
+
name = state["name"],
|
| 768 |
+
grade = state["grade"],
|
| 769 |
+
level = state["level"],
|
| 770 |
+
correct_total = total_correct,
|
| 771 |
+
q_total = total_qs,
|
| 772 |
+
avg_percent = avg_pct,
|
| 773 |
+
final_stars = ft
|
| 774 |
+
)
|
| 775 |
+
save_msg = "\n\nβ
**Results saved to Google Sheets.**"
|
| 776 |
+
except Exception as e:
|
| 777 |
+
save_msg = f"\n\nβ οΈ **Sheet save failed:** {e}"
|
| 778 |
+
|
| 779 |
+
# Build bonus feedback text
|
| 780 |
+
bonus_txt = "\n\n---\n### π Grammar Bonus Results\n"
|
| 781 |
+
for b in bonus_results:
|
| 782 |
+
bonus_txt += (f"\n**Q:** {b['question']}\n"
|
| 783 |
+
f"- Corrected: _{b['corrected_answer']}_\n"
|
| 784 |
+
f"- Your retry: _{b['student_retry']}_\n"
|
| 785 |
+
f"- Bonus: **{b['bonus_score']}/{max_bonus}** β {b['feedback']}\n")
|
| 786 |
+
bonus_txt += (f"\n**Avg bonus this round:** {avg_bonus:.2f} β\n"
|
| 787 |
+
f"**Round total:** {earned_this} earned + "
|
| 788 |
+
f"{avg_bonus:.2f} bonus = **{total_this:.2f} β**"
|
| 789 |
+
+ save_msg)
|
| 790 |
+
|
| 791 |
+
full_txt = state["result_text"] + bonus_txt
|
| 792 |
+
|
| 793 |
+
corr_hide = [gr.update(value="", visible=False) for _ in range(MAX_QUESTIONS)]
|
| 794 |
+
retry_hide = hide_pairs(MAX_QUESTIONS)
|
| 795 |
+
|
| 796 |
+
# If no more chunks, show a "Session complete" summary instead of next_btn
|
| 797 |
+
if not has_more:
|
| 798 |
+
n = len(state["chunk_earned_stars"])
|
| 799 |
+
ae = sum(state["chunk_earned_stars"]) / n if n else 0.0
|
| 800 |
+
ab = sum(state["chunk_bonus_stars"]) / n if n else 0.0
|
| 801 |
+
ft = ae + ab
|
| 802 |
+
|
| 803 |
+
breakdown = "\n| Chunk | Earned β | Bonus β | Total |\n|---|---|---|---|\n"
|
| 804 |
+
for k, (e, b) in enumerate(
|
| 805 |
+
zip(state["chunk_earned_stars"], state["chunk_bonus_stars"]), 1):
|
| 806 |
+
breakdown += f"| {k} | {e:.1f} | {b:.2f} | {e+b:.2f} |\n"
|
| 807 |
+
|
| 808 |
+
final_text = (
|
| 809 |
+
f"## π Session Complete!\n\n"
|
| 810 |
+
f"{breakdown}\n"
|
| 811 |
+
f"| Metric | Value |\n|---|---|\n"
|
| 812 |
+
f"| Chunks completed | {n} |\n"
|
| 813 |
+
f"| Avg earned stars | {ae:.2f} β |\n"
|
| 814 |
+
f"| Avg bonus stars | {ab:.2f} β |\n"
|
| 815 |
+
f"| **Final total stars** | **{ft:.2f} β** |"
|
| 816 |
+
+ save_msg
|
| 817 |
)
|
| 818 |
return (
|
| 819 |
+
[state,
|
| 820 |
+
gr.update(value=full_txt, visible=True), # result_md (shows bonus details)
|
| 821 |
+
gr.update(visible=False), # bonus_btn
|
| 822 |
+
gr.update(visible=False), # grading_msg
|
| 823 |
+
gr.update(visible=False), # grammar_hdr
|
| 824 |
+
gr.update(visible=False), # next_btn
|
| 825 |
+
gr.update(value=final_text, visible=True), # final_md β session summary
|
| 826 |
+
gr.update(active=False)] # stop timer
|
| 827 |
+
+ corr_hide
|
| 828 |
+
+ retry_hide
|
| 829 |
)
|
| 830 |
|
| 831 |
+
# More chunks remain β show next button
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 832 |
return (
|
| 833 |
+
[state,
|
| 834 |
+
gr.update(value=full_txt, visible=True), # result_md
|
| 835 |
+
gr.update(visible=False), # bonus_btn
|
| 836 |
+
gr.update(visible=False), # grading_msg
|
| 837 |
+
gr.update(visible=False), # grammar_hdr
|
| 838 |
+
gr.update(visible=True), # next_btn
|
| 839 |
+
gr.update(visible=False), # final_md
|
| 840 |
+
gr.update(active=False)] # stop timer
|
| 841 |
+
+ corr_hide
|
| 842 |
+
+ retry_hide
|
|
|
|
|
|
|
| 843 |
)
|
| 844 |
|
| 845 |
+
bonus_btn.click(
|
| 846 |
+
cb_bonus_start, inputs=[sess], outputs=[bonus_btn, grading_msg]
|
| 847 |
+
).then(
|
| 848 |
+
cb_bonus,
|
| 849 |
+
inputs=[sess] + gr_boxes,
|
| 850 |
+
outputs=([sess, result_md, bonus_btn, grading_msg,
|
| 851 |
+
grammar_hdr, next_btn, final_md, blank_timer]
|
| 852 |
+
+ corrected_boxes
|
| 853 |
+
+ [x for pair in zip(gi_boxes, gr_boxes) for x in pair])
|
| 854 |
+
)
|
| 855 |
+
|
| 856 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 857 |
+
# NEXT CHUNK
|
| 858 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 859 |
+
def cb_next(state):
|
| 860 |
+
load_next_chunk(state)
|
| 861 |
+
ci = state["current_indices"]
|
| 862 |
+
return ([state,
|
| 863 |
+
gr.update(value=f"## π Level {state['level']} β Passages {ci[0]}β{ci[-1]}", visible=True),
|
| 864 |
+
gr.update(value=state["current_passage"], visible=True),
|
| 865 |
+
gr.update(visible=True), # mode_row
|
| 866 |
+
gr.update(visible=True), # mode_check_row
|
| 867 |
+
gr.update(value=False, interactive=True), # disappearing_cb reset
|
| 868 |
+
gr.update(value=False, interactive=True), # static_cb reset
|
| 869 |
+
gr.update(visible=False), # submit_btn
|
| 870 |
+
gr.update(value="", visible=False), # result_md clear
|
| 871 |
+
gr.update(visible=False)] # next_btn hide
|
| 872 |
+
+ qa_ui(state["current_questions"], interactive=False))
|
| 873 |
+
|
| 874 |
+
next_btn.click(
|
| 875 |
cb_next,
|
| 876 |
inputs=[sess],
|
| 877 |
+
outputs=([sess, status_md, passage_bx,
|
| 878 |
+
mode_row, mode_check_row,
|
| 879 |
+
disappearing_cb, static_cb,
|
| 880 |
+
submit_btn, result_md, next_btn]
|
| 881 |
+
+ [x for pair in zip(q_boxes, a_boxes) for x in pair])
|
|
|
|
|
|
|
|
|
|
| 882 |
)
|
| 883 |
|
| 884 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|