Rajarshi255 commited on
Commit
5b0e574
Β·
verified Β·
1 Parent(s): cdddfa2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +780 -689
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
- from gtts import gTTS
 
38
  from openai import OpenAI
39
 
40
-
41
- # =========================================================
42
  # CONFIGURATION
43
- # =========================================================
44
 
45
- BASE_DIR = os.path.dirname(os.path.abspath(__file__))
46
 
47
- MAX_QUESTIONS = 6
48
- DEFAULT_SPEED = 0.7
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 get_llm_client():
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
- # GOOGLE SHEETS
74
- # Secret name : gcp_service_account (paste full service_account.json content)
75
- # Spreadsheet : 18oKXXwKMWE_CfKJGljWqRAKAIsp0SK6ffmkly2GHnxk
76
- # Tab : Scores
77
- # Columns : Date | Name | Classs | Result | Full Marks | Percentage | Star | Level
78
- # =========================================================
79
-
80
- SPREADSHEET_ID = "18oKXXwKMWE_CfKJGljWqRAKAIsp0SK6ffmkly2GHnxk"
81
- WORKSHEET_NAME = "Scores"
82
-
83
-
84
- def get_sheet():
85
- """Exact same pattern as the working reading-comprehension app."""
86
- import gspread
87
- from google.oauth2.service_account import Credentials
88
-
89
- svc_json = os.environ.get("gcp_service_account")
90
- if not svc_json:
91
- raise RuntimeError("gcp_service_account env var not set")
92
-
93
- creds = Credentials.from_service_account_info(
94
- json.loads(svc_json),
95
- scopes=["https://www.googleapis.com/auth/spreadsheets"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  )
97
- gc = gspread.authorize(creds)
98
- return gc.open_by_key(SPREADSHEET_ID).worksheet(WORKSHEET_NAME)
99
-
100
-
101
- def log_to_sheets(student_name, student_grade,
102
- result, full_marks, percent,
103
- final_stars, level_label):
104
- """
105
- Append one row β€” columns match Scores sheet exactly:
106
- Date | Name | Classs | Result | Full Marks | Percentage | Star | Level
107
- Returns "" on success, error string on failure.
108
- """
109
- try:
110
- sheet = get_sheet()
111
- row = [
112
- datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S"),
113
- student_name,
114
- student_grade,
115
- result,
116
- full_marks,
117
- round(float(percent), 1),
118
- final_stars,
119
- level_label,
 
 
120
  ]
121
- sheet.append_row(row, value_input_option="USER_ENTERED")
122
- print(f"[Sheets] βœ… Saved: {student_name} | stars={final_stars} | {percent:.1f}%")
123
- return ""
124
- except Exception as e:
125
- import traceback; traceback.print_exc()
126
- msg = f"{type(e).__name__}: {e}"
127
- print(f"[Sheets error] {msg}")
128
- return msg
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
- p = re.match(r'pssg(\d+)\.txt$', fname)
139
- q = re.match(r'(?:qstn|question)(\d+)\.txt$', fname)
140
- if p:
141
- idx = int(p.group(1))
142
  with open(os.path.join(BASE_DIR, fname), encoding="utf-8") as f:
143
  passages[idx] = f.read().strip()
144
- if q:
145
- idx = int(q.group(1))
146
  with open(os.path.join(BASE_DIR, fname), encoding="utf-8") as f:
147
- questions[idx] = [x.strip() for x in f if x.strip()]
148
  return passages, questions
149
 
 
 
 
 
 
 
150
 
151
- # =========================================================
152
- # AUDIO
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 min(3, max(1, level + 1))
177
-
178
 
179
- def raw_stars_from_score(correct, total):
180
- """
181
- Proportional stars based on number of correct answers.
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
- def compute_next_level(current, stars):
216
- if stars >= THRESHOLD_STAR:
217
- return current + 1
218
- if stars <= LOW_STAR_LIMIT:
219
- return max(0, current - 1)
220
  return current
221
 
 
 
 
 
 
 
 
222
 
223
- def stars_display(n):
224
- n = max(0, min(6, int(round(n))))
225
- return "⭐" * n + "β˜†" * max(0, 5 - n)
226
-
 
 
 
 
227
 
228
- # =========================================================
229
- # GRADING
230
- # =========================================================
 
231
 
232
- def grade_answers(passage, questions, answers):
233
- client = get_llm_client()
234
- if not client:
235
- return _fallback_grade(questions, answers)
236
-
237
- qa_block = "\n".join(
238
- f"Q{i+1}: {q}\nA{i+1}: {a}"
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
- try:
254
- response = client.chat.completions.create(
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
- "student_name": "",
284
- "student_grade": "",
 
285
  "level": 0,
286
- "passages": {},
287
- "questions": {},
288
- "indices": [],
289
- "ptr": 0,
290
- "round_num": 0,
291
- "speed": DEFAULT_SPEED,
292
- "transcript_mode": "disappearing",
293
- "current_passage": "",
294
- "current_questions": [],
295
- "current_chunk_ids": [],
296
- "audio_path": None,
297
- # transcript timer
298
- "transcript_shown_at": None,
299
- "transcript_hidden": True,
300
- # flow
301
- "awaiting_submit": False,
302
- "quiz_complete": False,
303
- # star accumulation
304
- "all_stars": [],
305
- "last_stars": 0,
306
- "last_percent": 0,
 
 
307
  }
308
 
309
-
310
- # =========================================================
311
- # CHUNK LOADING
312
- # =========================================================
313
-
314
  def load_next_chunk(state):
315
- size = passages_for_level(state["level"])
316
- chunk = state["indices"][state["ptr"]: state["ptr"] + size]
 
 
 
317
  if not chunk:
318
  return False
319
- passage_text = "\n\n".join(state["passages"][i] for i in chunk)
320
- qs = []
321
- for i in chunk:
322
- qs += state["questions"].get(i, [])
323
- qs = qs[:MAX_QUESTIONS]
324
- state["current_passage"] = passage_text
325
- state["current_questions"] = qs
326
- state["current_chunk_ids"] = chunk
327
- state["ptr"] += size
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 q_updates(q_list, visible):
341
- out = []
342
  for i in range(MAX_QUESTIONS):
343
- if visible and i < len(q_list):
344
- out.append(gr.update(value=f"**Q{i+1}:** {q_list[i]}", visible=True))
 
345
  else:
346
- out.append(gr.update(value="", visible=False))
347
- return out
 
348
 
 
 
349
 
350
- def a_updates(q_list, visible):
351
- out = []
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
- ANTI_COPY_JS = """
 
 
 
358
  <script>
359
- document.addEventListener('contextmenu', e => e.preventDefault());
360
- document.addEventListener('copy', e => e.preventDefault());
361
- document.addEventListener('selectstart', e => {
362
- if (e.target.tagName !== 'INPUT' && e.target.tagName !== 'TEXTAREA')
363
- e.preventDefault();
364
- });
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
365
  </script>
366
  """
367
 
368
-
369
- # =========================================================
370
- # BUILD UI
371
- # =========================================================
372
-
373
- with gr.Blocks(title="Adaptive Listening Quiz") as demo:
374
-
375
- gr.HTML(ANTI_COPY_JS)
376
- gr.Markdown("# 🎧 Adaptive Listening Comprehension Quiz")
377
-
378
- # ── LOGIN PANEL ────────────────────────────────────────
379
- with gr.Group(visible=True) as login_panel:
380
- gr.Markdown("### Student Login")
381
- inp_name = gr.Textbox(label="Student Name", placeholder="Enter your name")
382
- inp_grade = gr.Textbox(label="Class / Grade", placeholder="e.g. 6")
383
-
384
- # FIX 2: transcript mode radio β€” always rendered, never hidden
385
- inp_mode = gr.Radio(
386
- choices=["disappearing", "static", "none"],
387
- value="disappearing",
388
- label="Transcript Mode",
389
- info=(
390
- "disappearing = shown when audio starts, hides after 3 s | "
391
- "static = always visible | "
392
- "none = no transcript"
393
- ),
 
 
 
 
 
 
 
 
 
 
394
  )
395
- inp_speed = gr.Slider(0.5, 1.5, value=DEFAULT_SPEED, step=0.05,
396
- label="Audio Speed (0.5 = slowest)")
397
- login_error = gr.Markdown("")
398
- btn_start = gr.Button("β–Ά Start Quiz", variant="primary")
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
- gr.Markdown("---")
419
- gr.Markdown("#### Answer the questions below after listening")
 
 
420
 
421
- q_labels = [gr.Markdown(visible=False) for _ in range(MAX_QUESTIONS)]
422
- a_boxes = [gr.Textbox(label=f"Answer {i+1}", visible=False, lines=2)
423
- for i in range(MAX_QUESTIONS)]
424
 
425
- btn_submit = gr.Button("βœ… Submit Answers", variant="primary", visible=False)
426
- result_md = gr.Markdown("")
427
- btn_next = gr.Button("➑ Next Passage", visible=False)
428
 
429
- # ── DONE PANEL ─────────────────────────────────────────
430
- with gr.Group(visible=False) as done_panel:
431
- gr.Markdown("## πŸ† Quiz Complete!")
432
- done_md = gr.Markdown("")
433
 
434
- sess = gr.State(fresh_state())
435
 
 
 
 
 
436
 
437
- # ──────────────────────────────────────────────────────
438
- # START
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
- return (
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
- btn_start.click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
500
  cb_start,
501
- inputs=[inp_name, inp_grade, inp_mode, inp_speed, sess],
502
- outputs=[
503
- sess,
504
- login_panel, quiz_panel, done_panel,
505
- status_md,
506
- audio_out, transcript_box, timer_html, result_md,
507
- *q_labels, *a_boxes,
508
- btn_submit, btn_next, btn_replay,
509
- done_md,
510
- ],
511
  )
512
 
513
-
514
- # ──────────────────────────────────────────────────────
515
- # FIX 3: AUDIO PLAY β†’ show transcript immediately
516
- # The transcript appears the moment audio starts, not after it ends.
517
- # In "disappearing" mode the 3-second countdown begins here.
518
- # ──────────────────────────────────────────────────────
519
-
520
- def cb_audio_play(state):
521
- mode = state["transcript_mode"]
522
-
523
- if mode == "disappearing":
524
- transcript_val = state["current_passage"]
525
- state["transcript_shown_at"] = time.time()
526
- state["transcript_hidden"] = False
527
- timer_val = (
528
- f"<p style='color:darkorange;font-weight:bold'>"
529
- f"πŸ“– Transcript visible for {TRANSCRIPT_SHOW_SECS}s…</p>"
530
- )
531
- elif mode == "static":
532
- transcript_val = state["current_passage"]
533
- state["transcript_shown_at"] = None
534
- state["transcript_hidden"] = False
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
- # AUDIO STOP β†’ reveal question boxes
553
- # Transcript state is left exactly as the timer left it.
554
- # ──────────────────────────────────────────────────────
555
-
556
- def cb_audio_ended(state):
557
- state["awaiting_submit"] = True
558
- return (
559
- state,
560
- *q_updates(state["current_questions"], True),
561
- *a_updates(state["current_questions"], True),
562
- gr.update(visible=True), # submit
563
- gr.update(visible=False), # next
564
- )
565
-
566
- audio_out.stop(
567
- cb_audio_ended,
568
- inputs=[sess],
569
- outputs=[
570
- sess,
571
- *q_labels, *a_boxes,
572
- btn_submit, btn_next,
573
- ],
574
  )
575
 
 
 
 
 
 
 
576
 
577
- # ──────────────────────────────────────────────────────
578
- # TIMER β€” hides disappearing transcript after 3 s
579
- # Fires every 1 second; does NOT touch anything else.
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
- result = grade_answers(state["current_passage"], questions, answers)
625
- percent = result.get("percent", 0)
626
- correct_count = result.get("correct_count", 0)
627
- total_q = result.get("total_questions", len(questions))
628
- feedback = result.get("feedback", [])
629
-
630
- raw_stars = raw_stars_from_score(correct_count, total_q)
631
- bonus_star = (correct_count >= total_q and total_q > 0)
632
- final_stars = min(6, raw_stars + (1 if bonus_star else 0))
633
-
634
- state["last_stars"] = final_stars
635
- state["last_percent"] = percent
636
- state["round_num"] += 1
637
- state["all_stars"].append(final_stars)
638
-
639
- # Build level label: audible-<transcript_mode>-<level>
640
- level_label = f"audible-{state['transcript_mode']}-{state['level']}"
641
-
642
- # Log to Sheets β€” capture error to show in UI
643
- sheets_err = log_to_sheets(
644
- student_name = state["student_name"],
645
- student_grade = state["student_grade"],
646
- result = correct_count,
647
- full_marks = total_q,
648
- percent = percent,
649
- final_stars = final_stars,
650
- level_label = level_label,
651
- )
652
- sheets_status = (
653
- "\n\nβœ… **Saved to Google Sheets**"
654
- if not sheets_err
655
- else f"\n\n⚠️ **Sheets error:** `{sheets_err}`"
656
- )
657
-
658
- # Result display
659
- bonus_text = " 🌟 **BONUS STAR** for perfect score!" if bonus_star else ""
660
- fb_lines = []
661
- for i, (q, a) in enumerate(zip(questions, answers)):
662
- if not q.strip():
663
- continue
664
- fb = feedback[i] if i < len(feedback) else ""
665
- fb_lines.append(f"- **Q{i+1}:** {fb}")
666
-
667
- avg_so_far = (round(sum(state["all_stars"]) / len(state["all_stars"]), 2)
668
- if state["all_stars"] else 0)
669
-
670
- result_text = (
671
- f"### Results\n"
672
- f"**Score:** {correct_count}/{total_q} ({percent:.0f}%)\n\n"
673
- f"**Stars:** {stars_display(final_stars)} ({final_stars}/5){bonus_text}\n\n"
674
- f"**Running average:** {avg_so_far:.2f} / 5\n\n"
675
- + ("\n".join(fb_lines) if fb_lines else "")
676
- + sheets_status
677
- )
678
-
679
- state["awaiting_submit"] = False
680
- more = state["ptr"] < len(state["indices"])
681
-
682
- # FIX 3: do NOT touch transcript_box or timer_html here
683
- return (
684
- state,
685
- result_text,
686
- gr.update(visible=False),
687
- gr.update(visible=more),
688
- gr.update(), # transcript β€” untouched
689
- gr.update(), # timer β€” untouched
690
- )
691
-
692
- btn_submit.click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
693
  cb_submit,
694
- inputs=[sess, *a_boxes],
695
- outputs=[sess, result_md, btn_submit, btn_next, transcript_box, timer_html],
 
 
 
696
  )
697
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
698
 
699
- # ──────────────────────────────────────────────────────
700
- # NEXT
701
- # ──────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
702
 
703
- def cb_next(state):
704
- state["level"] = compute_next_level(state["level"], state["last_stars"])
705
- ok = load_next_chunk(state)
706
-
707
- if not ok:
708
- state["quiz_complete"] = True
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
- done_text = (
724
- f"### Well done, **{state['student_name']}**!\n\n"
725
- f"You completed all {state['round_num']} rounds.\n\n"
726
- f"**Final Level:** {state['level']}\n\n"
727
- f"**Average Stars:** {avg:.2f} / 5 {stars_display(round(avg))}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
728
  )
729
  return (
730
- state,
731
- gr.update(visible=False), gr.update(visible=True),
732
- done_text, "", None, "", "", "",
733
- *q_updates([], False), *a_updates([], False),
734
- gr.update(visible=False), gr.update(visible=False),
735
- gr.update(visible=False),
 
 
 
 
736
  )
737
 
738
- total = len(state["indices"])
739
- status_text = (
740
- f"### Level {state['level']} | "
741
- f"Passage {state['ptr']} of {total}"
742
- )
743
-
744
  return (
745
- state,
746
- gr.update(visible=True), gr.update(visible=False),
747
- "",
748
- status_text,
749
- state["audio_path"],
750
- "", # transcript blank β€” cb_audio_play will fill it
751
- "", "",
752
- *q_updates(state["current_questions"], False),
753
- *a_updates([], False),
754
- gr.update(visible=False),
755
- gr.update(visible=False),
756
- gr.update(visible=True),
757
  )
758
 
759
- btn_next.click(
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
760
  cb_next,
761
  inputs=[sess],
762
- outputs=[
763
- sess,
764
- quiz_panel, done_panel, done_md,
765
- status_md,
766
- audio_out, transcript_box, timer_html, result_md,
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()