Rajarshi255 commited on
Commit
beb6c64
·
verified ·
1 Parent(s): 4ec674f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +245 -495
app.py CHANGED
@@ -1,531 +1,281 @@
1
- import os, re, csv, json, time, datetime
2
  from typing import List, Dict, Tuple
3
  import gradio as gr
4
  from openai import OpenAI
5
  import httpx
6
 
7
- # ===================== CONFIG =====================
8
-
9
  DEFAULT_TIMEOUT = 25
10
  MIN_WORDS = 5
 
 
11
 
12
- # DeepSeek (primary)
13
  DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
14
  DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
15
  DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
16
 
17
- # OpenAI (fallback)
18
- OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
19
- OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
20
-
21
- # Google Sheets
22
- SHEETS_SPREADSHEET_ID = os.getenv("SHEETS_SPREADSHEET_ID", "18oKXXwKMWE_CfKJGljWqRAKAIsp0SK6ffmkly2GHnxk")
23
- SHEETS_WORKSHEET_ID = int(os.getenv("SHEETS_WORKSHEET_ID", "1659517197"))
24
- SERVICE_ACCOUNT_JSON = os.getenv("GOOGLE_SERVICE_ACCOUNT_JSON") # full JSON
25
 
26
- # ===================== PATHS ======================
 
 
27
 
28
- def _base_dir():
29
- try:
30
- return os.path.dirname(os.path.abspath(__file__))
31
- except NameError:
32
- return os.getcwd()
33
-
34
- BASE_DIR = _base_dir()
35
  PASSAGE_TXT = os.path.join(BASE_DIR, "passage.txt")
36
  QUESTION_TXT = os.path.join(BASE_DIR, "question.txt")
37
  CSV_PATH = os.path.join(BASE_DIR, "responses.csv")
38
 
39
- def _make_http_client():
40
- return httpx.Client(timeout=DEFAULT_TIMEOUT)
41
-
42
- # ===================== PARSERS ====================
43
-
44
- def read_text_file(path: str) -> List[str]:
45
- if not os.path.exists(path):
46
- raise FileNotFoundError(f"Missing '{path}'. Put it next to app.py.")
47
- with open(path, "r", encoding="utf-8") as f:
48
- return [line.rstrip("\n") for line in f]
49
-
50
- def parse_passages(lines: List[str]) -> Dict[int, str]:
51
- passages, current = {}, None
52
- header_re = re.compile(r'^\s*passage\s*-\s*(\d+)\s*$', re.I)
53
- for line in lines:
54
- m = header_re.match(line or "")
55
- if m:
56
- current = int(m.group(1)); passages[current] = []
57
- elif current:
58
- passages[current].append(line)
59
- if not passages:
60
- text = "\n".join(lines).strip()
61
- return {1: text} if text else {}
62
- return {k: "\n".join(v).strip() for k, v in passages.items()}
63
-
64
- def parse_question_sets(lines: List[str]) -> Dict[int, List[str]]:
65
- sets, current = {}, None
66
- header_re = re.compile(r'^\s*question\s*set\s*(\d+)\s*$', re.I)
67
- qnum_re = re.compile(r'^\s*(\d+)[\.\)]\s*(.+)$')
68
- for raw in lines:
69
- raw = (raw or "").strip()
70
- if not raw: continue
71
- head = header_re.match(raw)
72
- if head:
73
- current = int(head.group(1)); sets[current] = []; continue
74
- if current is not None:
75
- m = qnum_re.match(raw)
76
- if m:
77
- q = m.group(2).strip()
78
- if not q.endswith("?"): q += "?"
79
- sets[current].append(f"{m.group(1)}) {q}")
80
- else:
81
- q = raw if raw.endswith("?") else raw + "?"
82
- sets[current].append(q)
83
- if not sets:
84
- fallback = []
85
- for raw in lines:
86
- raw = (raw or "").strip()
87
- if not raw: continue
88
- m = qnum_re.match(raw)
89
- if m:
90
- q = m.group(2).strip()
91
- if not q.endswith("?"): q += "?"
92
- fallback.append(f"{m.group(1)}) {q}")
93
- else:
94
- q = raw if raw.endswith("?") else raw + "?"
95
- fallback.append(q)
96
- return {1: fallback} if fallback else {}
97
- return sets
98
-
99
- def load_passages_and_questions(pfile, qfile):
100
- p_lines = read_text_file(pfile)
101
- q_lines = read_text_file(qfile)
102
- passages = parse_passages(p_lines)
103
- qsets = parse_question_sets(q_lines)
104
- stories = []
105
- for idx in sorted(set(passages) & set(qsets)):
106
- stories.append({
107
- "index": idx,
108
- "title": f"Passage {idx}",
109
- "passage": passages[idx],
110
- "questions": qsets[idx]
111
- })
112
- return stories
113
-
114
- # ===================== UTILS ======================
115
-
116
- def word_count(text):
117
- return len(re.findall(r"[A-Za-z0-9’']+", text or ""))
118
-
119
- def compute_stars(p):
120
- if p >= 90: return 5
121
- if p >= 80: return 4
122
- if p >= 70: return 3
123
- if p >= 60: return 2
124
- if p >= 50: return 1
125
- return 0
126
-
127
- def save_response_csv(path, name, klass, title, questions, answers, percent, stars):
128
- new = not os.path.exists(path)
129
- with open(path, "a", newline="", encoding="utf-8") as f:
130
- w = csv.writer(f)
131
- if new:
132
- w.writerow(["Timestamp", "StudentName", "Class", "StoryTitle"] +
133
- [f"Q{i+1}" for i in range(len(questions))] +
134
- ["Percent", "StarsAwarded"])
135
- ts = datetime.datetime.now().isoformat(timespec="seconds")
136
- w.writerow([ts, name, klass, title] + list(answers) + [percent, stars])
137
-
138
- # -------- Google Sheets (append Timestamp, Name, Class, Stars)
139
- '''def write_stars_to_google_sheet(name: str, klass: str, stars: int) -> str | None:
140
- """
141
- Appends one row to the target Google Sheet:
142
- [Timestamp, Name, Class, StarsAwarded].
143
-
144
- Returns:
145
- None on success, or an error string if something went wrong.
146
- """
147
- if not SERVICE_ACCOUNT_JSON:
148
- return "GOOGLE_SERVICE_ACCOUNT_JSON env var not set."
149
- try:
150
- import gspread
151
- from google.oauth2.service_account import Credentials
152
- scopes = ["https://www.googleapis.com/auth/spreadsheets"]
153
- info = json.loads(SERVICE_ACCOUNT_JSON)
154
- creds = Credentials.from_service_account_info(info, scopes=scopes)
155
- gc = gspread.authorize(creds)
156
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  sh = gc.open_by_key(SHEETS_SPREADSHEET_ID)
158
- ws = None
159
- for w in sh.worksheets():
160
- if w.id == SHEETS_WORKSHEET_ID:
161
- ws = w; break
162
- if ws is None:
163
- ws = sh.sheet1 # fallback
164
-
165
- ts = datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S")
166
- ws.append_row([ts, name, klass, stars], value_input_option="USER_ENTERED")
167
- return None
 
 
 
 
 
 
 
 
168
  except Exception as e:
169
- return f"Sheets write failed: {e}"'''
170
 
171
- '''def write_stars_to_google_sheet(name: str, klass: str, stars: int, percent: int, total_q: int, correct_q: int) -> str | None:
172
- # Use the environment variable name that you confirmed works
173
- env_json = os.environ.get("gcp_service_account")
174
- if not env_json:
175
- return "Secret 'gcp_service_account' not found."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
176
 
177
  try:
178
- import gspread
179
- from google.oauth2.service_account import Credentials
 
 
 
 
 
 
 
 
 
 
 
 
 
 
180
 
181
- scope = ["https://www.googleapis.com/auth/spreadsheets"]
182
- service_info = json.loads(env_json)
183
- creds = Credentials.from_service_account_info(service_info, scopes=scope)
184
- gc = gspread.authorize(creds)
 
 
 
185
 
186
- # Target Spreadsheet ID and Worksheet Name
187
- sheet = gc.open_by_key("18oKXXwKMWE_CfKJGljWqRAKAIsp0SK6ffmkly2GHnxk").worksheet("Scores")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
 
189
- # MAPPING TO YOUR 8 COLUMNS:
190
- # [Date, Name, Classs, Result, Full Marks, Percentage, Star, Level]
191
- row = [
192
- datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S"), # Date
193
- name, # Name
194
- klass, # Classs
195
- correct_q, # Result (Correct answers)
196
- total_q, # Full Marks
197
- f"{percent}%", # Percentage
198
- stars, # Star
199
- "Reading Comprehension" # Level (Module name)
200
- ]
201
 
202
- sheet.append_row(row, value_input_option="USER_ENTERED")
203
- return None
204
- except Exception as e:
205
- return f"Sheet Error: {e}"'''
206
- def write_stars_to_google_sheet(name, grade, stars, correct, total, percent):
207
- import os, json, datetime, gspread
208
- from google.oauth2.service_account import Credentials
209
-
210
- # This looks for the secret you just added in the Settings tab
211
- service_account_json = os.environ.get("gcp_service_account")
212
-
213
- if not service_account_json:
214
- # This will show up in your Hugging Face "Logs" if it fails
215
- print("SECRET ERROR: 'gcp_service_account' not found in Environment Variables.")
216
- return "Secret missing"
217
 
218
- try:
219
- scope = ["https://www.googleapis.com/auth/spreadsheets"]
220
- service_info = json.loads(service_account_json)
221
- creds = Credentials.from_service_account_info(service_info, scopes=scope)
222
- gc = gspread.authorize(creds)
223
 
224
- sh = gc.open_by_key("18oKXXwKMWE_CfKJGljWqRAKAIsp0SK6ffmkly2GHnxk")
225
- sheet = sh.worksheet("Scores")
 
 
226
 
227
- # Mapping to your 8-column CSV structure
228
- row = [
229
- datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S"),
230
- name,
231
- grade,
232
- correct,
233
- total,
234
- f"{percent}%",
235
- stars,
236
- "Comprehension--Reading"
237
- ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
 
239
- sheet.append_row(row, value_input_option="USER_ENTERED")
240
- return None # Success
 
 
 
 
 
 
 
 
 
 
241
 
242
- except Exception as e:
243
- print(f"GOOGLE SHEET ERROR: {e}")
244
- return str(e)
245
-
246
- # ===================== LLM HELPERS =================
247
-
248
- def _strip_json(raw: str) -> str:
249
- s = (raw or "").strip()
250
- if s.startswith("```"):
251
- s = s.strip("`")
252
- s = s.replace("json", "", 1).strip()
253
- return s
254
-
255
- def _client_for_primary():
256
- if not DEEPSEEK_API_KEY:
257
- return None
258
- return OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL, http_client=_make_http_client())
259
-
260
- def _client_for_fallback():
261
- if not OPENAI_API_KEY:
262
- return None
263
- return OpenAI(api_key=OPENAI_API_KEY, http_client=_make_http_client())
264
-
265
- # ---- Grading (content correctness)
266
- def build_grading_prompt(story, passage, qas):
267
- return f"""You are a precise reading comprehension grader.
268
- Judge ONLY factual correctness based on the passage. Do NOT judge grammar.
269
- Return JSON with fields:
270
- total_questions, correct_count, percent, details (question, student_answer, is_correct, reference_answer).
271
- DATA:
272
- {json.dumps({'story_title': story, 'passage': passage, 'qa_pairs': [{'question':q,'student_answer':a} for q,a in qas]}, indent=2)}"""
273
-
274
- def grade_answers(story, passage, qas):
275
- errors = []
276
- # primary
277
- c = _client_for_primary()
278
- if c:
279
- try:
280
- r = c.chat.completions.create(
281
- model=DEEPSEEK_MODEL, temperature=0,
282
- messages=[{"role":"system","content":"You are a grading engine."},
283
- {"role":"user","content":build_grading_prompt(story, passage, qas)}]
284
- )
285
- data = json.loads(_strip_json(r.choices[0].message.content))
286
- return data, f"DeepSeek ({DEEPSEEK_MODEL})", None
287
- except Exception as e:
288
- errors.append(f"DeepSeek: {e}")
289
- # fallback
290
- c2 = _client_for_fallback()
291
- if c2:
292
- try:
293
- r = c2.chat.completions.create(
294
- model=OPENAI_MODEL, temperature=0,
295
- messages=[{"role":"system","content":"You are a grading engine."},
296
- {"role":"user","content":build_grading_prompt(story, passage, qas)}]
297
- )
298
- data = json.loads(_strip_json(r.choices[0].message.content))
299
- return data, f"OpenAI ({OPENAI_MODEL})", None
300
- except Exception as e:
301
- errors.append(f"OpenAI: {e}")
302
-
303
- total = len(qas)
304
- d = {"total_questions": total, "correct_count": 0, "percent": 0,
305
- "details": [{"question": q, "student_answer": a, "is_correct": False, "reference_answer": ""} for q,a in qas]}
306
- note = " | ".join(errors) if errors else "All APIs failed"
307
- return d, "Fallback", note
308
-
309
- # ---- Grammar feedback (separate; does not affect score)
310
- def _grammar_prompt(answers: List[str]) -> str:
311
- return """You are a careful English grammar teacher.
312
- For each student answer, identify the main grammar issues and provide a concise corrected sentence that preserves the student's meaning.
313
- Return STRICT JSON array of objects: [{ "index": <0-based>, "issues": "<one-line summary>", "corrected": "<corrected sentence>" }].
314
- Do NOT include extra keys, commentary, or markdown code fences.
315
- Answers:
316
- """ + json.dumps(answers, ensure_ascii=False)
317
-
318
- def grammar_feedback_for_answers(answers: List[str]) -> List[Dict]:
319
- """
320
- Returns list of {index, issues, corrected} with same length as answers where possible.
321
- On failure, returns [].
322
- """
323
- # primary
324
- c = _client_for_primary()
325
- if c:
326
- try:
327
- r = c.chat.completions.create(
328
- model=DEEPSEEK_MODEL, temperature=0,
329
- messages=[{"role":"system","content":"You provide grammar feedback only."},
330
- {"role":"user","content":_grammar_prompt(answers)}]
331
- )
332
- data = json.loads(_strip_json(r.choices[0].message.content))
333
- if isinstance(data, list):
334
- return data
335
- except Exception:
336
- pass
337
- # fallback
338
- c2 = _client_for_fallback()
339
- if c2:
340
- try:
341
- r = c2.chat.completions.create(
342
- model=OPENAI_MODEL, temperature=0,
343
- messages=[{"role":"system","content":"You provide grammar feedback only."},
344
- {"role":"user","content":_grammar_prompt(answers)}]
345
- )
346
- data = json.loads(_strip_json(r.choices[0].message.content))
347
- if isinstance(data, list):
348
- return data
349
- except Exception:
350
- pass
351
- return []
352
-
353
- # ===================== SESSION HELPERS =============
354
-
355
- def init_story_session(qs): return 0, ["" for _ in qs], False, ""
356
- def show_current_question(i, qs):
357
- return (f"Question {i+1} of {len(qs)}", qs[i]) if 0 <= i < len(qs) else ("All done.", "")
358
- def record_answer(i, ans, txt):
359
- if 0 <= i < len(ans): ans[i] = (txt or "").strip()
360
- return ans
361
- def next_index(i, qs): return min(i+1, len(qs))
362
-
363
- # ===================== FINALIZE ====================
364
-
365
- def finalize_story(title, passage, questions, answers, name, klass):
366
- # Ensure answers list length
367
- if len(answers) < len(questions):
368
- answers = answers + [""] * (len(questions) - len(answers))
369
-
370
- qas = list(zip(questions, answers))
371
- result, who, err = grade_answers(title, passage, qas)
372
-
373
- # Robust percent (ignore model's percent if needed)
374
- total = int(result.get("total_questions") or len(questions))
375
- correct = int(result.get("correct_count") or sum(1 for d in result.get("details", []) if d.get("is_correct")))
376
- percent = round(100.0 * correct / total) if total else 0
377
- stars = compute_stars(percent)
378
-
379
- # Grammar feedback (independent from scoring)
380
- grammar = grammar_feedback_for_answers(answers)
381
- grammar_by_index = {g.get("index"): g for g in grammar if isinstance(g, dict) and "index" in g}
382
-
383
- # Persist
384
- save_response_csv(CSV_PATH, name, klass, title, questions, answers, percent, stars)
385
- #sheets_note = write_stars_to_google_sheet(name, klass, stars)
386
- # Change this line:
387
- # sheets_note = write_stars_to_google_sheet(name, klass, stars)
388
-
389
- # To this:
390
- sheets_note = write_stars_to_google_sheet(name, klass, stars, percent, total, correct)
391
-
392
- # Build UI text
393
- lines = []
394
- lines.append(f"# Well done, {name}!")
395
- lines.append(f"## You earned {stars} Stars! {'⭐' * stars}")
396
- lines.append("---") # A horizontal line separator
397
- lines.append(f"### {title} — Results")
398
- lines.append(f"**Graded by:** {who}" + (f" _(note: {err})_" if err else ""))
399
- lines.append(f"**Score:** {percent}% (**Correct:** {correct}/{total})")
400
- if sheets_note:
401
- lines.append(f"_Note: {sheets_note}_")
402
-
403
- # Merge correctness + grammar per question
404
- for idx, d in enumerate(result.get("details", [])):
405
- tick = "✅" if d.get("is_correct") else "❌"
406
- lines.append(f"- {tick} {d.get('question')}")
407
- lines.append(f" - Your answer: {d.get('student_answer') or '(blank)'}")
408
- ref = d.get("reference_answer", "")
409
- if ref:
410
- lines.append(f" - Reference: {ref}")
411
- g = grammar_by_index.get(idx)
412
- if g:
413
- if g.get("issues"):
414
- lines.append(f" - Grammar: {g['issues']}")
415
- if g.get("corrected"):
416
- lines.append(f" - Suggestion: {g['corrected']}")
417
-
418
- stars_line = "⭐" * stars if stars > 0 else "No stars this time — keep going!"
419
- return "\n".join(lines), stars_line
420
-
421
- # ===================== UI =========================
422
-
423
- with gr.Blocks(title="Reading Comprehension — From TXT Files") as demo:
424
- try:
425
- STORIES = load_passages_and_questions(PASSAGE_TXT, QUESTION_TXT)
426
- load_msg = ""
427
- except Exception as e:
428
- STORIES = []; load_msg = f"⚠️ {e}"
429
-
430
- gr.Markdown("# Reading Comprehension — From TXT Files")
431
- gr.Markdown("**Read each passage carefully, then answer the questions.**" if not load_msg else f"**{load_msg}**")
432
-
433
- with gr.Row():
434
- student_name = gr.Textbox(label="Student Name")
435
- student_class = gr.Textbox(label="Class")
436
-
437
- story_idx_state = gr.State(0)
438
- q_idx_state = gr.State(0)
439
- answers_state = gr.State([])
440
- finished_state = gr.State(False)
441
- stories_state = gr.State(STORIES)
442
-
443
- story_title_md = gr.Markdown()
444
- passage_box = gr.Textbox(label="Passage", interactive=False, lines=16)
445
- progress_md = gr.Markdown()
446
- question_md = gr.Markdown()
447
- answer_box = gr.Textbox(label="Your Answer", lines=3,
448
- placeholder=f"Write at least {MIN_WORDS} words.")
449
- notice_md = gr.Markdown(value="", visible=False)
450
- results_md = gr.Markdown(visible=False)
451
- stars_md = gr.Markdown(visible=False)
452
-
453
- with gr.Row():
454
- btn_save_next = gr.Button("Save Answer & Next", variant="primary")
455
- btn_finish = gr.Button("Finish This Story & Grade", variant="secondary")
456
- btn_next_story = gr.Button("Next Story ▶", variant="secondary")
457
-
458
- # on load
459
- def _on_load(stories):
460
- if not stories:
461
- return (0, 0, [], False, "No stories loaded.", "", "—", "—", "", gr.update(value="", visible=False))
462
- sidx = 0; story = stories[sidx]
463
- qidx, answers, finished, _ = init_story_session(story["questions"])
464
- prog, qtext = show_current_question(qidx, story["questions"])
465
- return (sidx, qidx, answers, finished, f"### {story['title']}",
466
- story["passage"], prog, qtext, "", gr.update(value="", visible=False))
467
-
468
- demo.load(_on_load, inputs=[stories_state],
469
- outputs=[story_idx_state, q_idx_state, answers_state, finished_state,
470
- story_title_md, passage_box, progress_md, question_md, answer_box, notice_md])
471
-
472
- # Save & Next
473
- def on_save_next(sidx, qidx, answers, ans_text, stories):
474
- if not stories:
475
- return qidx, answers, "—", "—", ans_text, gr.update(value="No stories loaded.", visible=True)
476
- wc = word_count(ans_text)
477
- if wc < MIN_WORDS:
478
- story = stories[sidx]
479
- prog, qtext = show_current_question(qidx, story["questions"])
480
- msg = f"⚠️ Please write at least {MIN_WORDS} words (you wrote {wc})."
481
- return qidx, answers, prog, qtext, ans_text, gr.update(value=msg, visible=True)
482
- story = stories[sidx]
483
- answers = record_answer(qidx, answers, ans_text)
484
- qidx = next_index(qidx, story["questions"])
485
- prog, qtext = show_current_question(qidx, story["questions"])
486
- return qidx, answers, prog, qtext, "", gr.update(value="", visible=False)
487
-
488
- btn_save_next.click(on_save_next,
489
- inputs=[story_idx_state, q_idx_state, answers_state, answer_box, stories_state],
490
- outputs=[q_idx_state, answers_state, progress_md, question_md, answer_box, notice_md])
491
-
492
- # Finish & Grade (capture current textbox too)
493
- def on_finish(sidx, qidx, answers, current_text, name, klass, stories):
494
- if not stories:
495
- yield gr.update(value="No stories to grade.", visible=True), gr.update(value="", visible=True), True
496
- return
497
- story = stories[sidx]
498
- if 0 <= qidx < len(story["questions"]) and (current_text or "").strip():
499
- answers = record_answer(qidx, answers or ["" for _ in story["questions"]], current_text)
500
-
501
- yield gr.update(value="⏳ Please wait... your answers are being evaluated.", visible=True), gr.update(value="", visible=False), False
502
  try:
503
- results, stars_line = finalize_story(story["title"], story["passage"], story["questions"], answers or [], name, klass)
504
- yield gr.update(value=results, visible=True), gr.update(value=f"**Stars Awarded:** {stars_line}", visible=True), True
505
- except Exception as e:
506
- yield gr.update(value=f"❌ Grading failed: {e}", visible=True), gr.update(value="", visible=False), False
507
-
508
- btn_finish.click(on_finish,
509
- inputs=[story_idx_state, q_idx_state, answers_state, answer_box, student_name, student_class, stories_state],
510
- outputs=[results_md, stars_md, finished_state],
511
- show_progress="full")
512
-
513
- # Next Story
514
- def on_next_story(sidx, stories):
515
- if not stories:
516
- return (sidx, 0, [], False, "No stories loaded.", "", "—", "—", "", gr.update(value="", visible=False))
517
- next_s = sidx + 1
518
- if next_s >= len(stories):
519
- return (sidx, 0, [], False, "### All stories finished.", "(Great work!)", "—", "—", "", gr.update(value="", visible=False))
520
- story = stories[next_s]
521
- qidx, answers, finished, _ = init_story_session(story["questions"])
522
- prog, qtext = show_current_question(qidx, story["questions"])
523
- return (next_s, qidx, answers, False, f"### {story['title']}", story["passage"], prog, qtext, "", gr.update(value="", visible=False))
524
-
525
- btn_next_story.click(on_next_story,
526
- inputs=[story_idx_state, stories_state],
527
- outputs=[story_idx_state, q_idx_state, answers_state, finished_state,
528
- story_title_md, passage_box, progress_md, question_md, answer_box, notice_md])
529
 
530
  if __name__ == "__main__":
531
- demo.launch()
 
1
+ import os, re, csv, json, time, datetime, random
2
  from typing import List, Dict, Tuple
3
  import gradio as gr
4
  from openai import OpenAI
5
  import httpx
6
 
7
+ # ===================== CONFIGURATION =====================
 
8
  DEFAULT_TIMEOUT = 25
9
  MIN_WORDS = 5
10
+ QUIZ_LIMIT_MINUTES = 45
11
+ SET_WORDS = 20
12
 
13
+ # API Keys (from Environment)
14
  DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY")
15
  DEEPSEEK_BASE_URL = os.getenv("DEEPSEEK_BASE_URL", "https://api.deepseek.com/v1")
16
  DEEPSEEK_MODEL = os.getenv("DEEPSEEK_MODEL", "deepseek-chat")
17
 
18
+ OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
19
+ OPENAI_MODEL = os.getenv("OPENAI_MODEL", "gpt-4o-mini")
 
 
 
 
 
 
20
 
21
+ # Google Sheets IDs
22
+ SHEETS_SPREADSHEET_ID = "18oKXXwKMWE_CfKJGljWqRAKAIsp0SK6ffmkly2GHnxk"
23
+ WORD_SOURCE_ID = "1ttx2D07Xp5SBdm1OFHCjcwcHf1yMTxFRxmx6NNERjHQ"
24
 
25
+ # Paths
26
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__)) if "__file__" in locals() else os.getcwd()
 
 
 
 
 
27
  PASSAGE_TXT = os.path.join(BASE_DIR, "passage.txt")
28
  QUESTION_TXT = os.path.join(BASE_DIR, "question.txt")
29
  CSV_PATH = os.path.join(BASE_DIR, "responses.csv")
30
 
31
+ # ===================== GOOGLE SHEETS & LOGIC HELPERS =====================
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ def get_gspread_client():
34
+ import gspread
35
+ from google.oauth2.service_account import Credentials
36
+ env_json = os.environ.get("gcp_service_account")
37
+ if not env_json: return None
38
+ scope = ["https://www.googleapis.com/auth/spreadsheets"]
39
+ creds = Credentials.from_service_account_info(json.loads(env_json), scopes=scope)
40
+ return gspread.authorize(creds)
41
+
42
+ def check_direct_entry(name, klass):
43
+ """Step 0: Check if student has 3+ stars in 'week' or 'cumulative' level this week."""
44
+ gc = get_gspread_client()
45
+ if not gc: return False, "Auth Error: Secret 'gcp_service_account' missing."
46
+ try:
47
  sh = gc.open_by_key(SHEETS_SPREADSHEET_ID)
48
+ sheet = sh.worksheet("Scores")
49
+ data = sheet.get_all_values()
50
+
51
+ # Calculate Monday of current week
52
+ now = datetime.datetime.now()
53
+ monday = (now - datetime.timedelta(days=now.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
54
+
55
+ cleaned_name = name.strip().lower()
56
+ for row in data[1:]:
57
+ try:
58
+ row_date = datetime.datetime.strptime(row[0], "%m/%d/%Y %H:%M:%S")
59
+ if row_date >= monday and row[1].strip().lower() == cleaned_name and str(row[2]) == str(klass):
60
+ stars = float(row[6] or 0)
61
+ lvl = row[7].lower()
62
+ if ("week" in lvl or "cumulative" in lvl) and stars >= 3:
63
+ return True, "Direct Entry Granted (3+ Stars this week)"
64
+ except: continue
65
+ return False, "Gateway Check Required"
66
  except Exception as e:
67
+ return False, f"Sheets Error: {str(e)}"
68
 
69
+ def get_words_for_gateway(klass):
70
+ """Step 1 & 2: Pull specific word ranges based on March 1st-3rd schedule."""
71
+ gc = get_gspread_client()
72
+ if not gc: return [["Error", "Auth Failed"]]
73
+
74
+ today = datetime.datetime.now().date()
75
+ MAR_01_SUN = datetime.date(2026, 3, 1)
76
+ MAR_02_MON = datetime.date(2026, 3, 2)
77
+ MAR_03_TUE = datetime.date(2026, 3, 3)
78
+
79
+ class_base = 0 if int(klass) <= 5 else 260
80
+
81
+ # Range Mapping per User Instruction
82
+ if today == MAR_01_SUN:
83
+ start, end = class_base + 61, class_base + 80
84
+ elif today == MAR_02_MON:
85
+ start, end = class_base + 76, class_base + 80
86
+ elif today >= MAR_03_TUE:
87
+ start, end = class_base + 81, class_base + 100
88
+ else: # Default fallback
89
+ start, end = class_base + 61, class_base + 80
90
 
91
  try:
92
+ sh = gc.open_by_key(WORD_SOURCE_ID)
93
+ ws = sh.worksheet("words")
94
+ rows = ws.get(f"A{start}:B{end}")
95
+ # Select 5 random words if the pool is larger than 5
96
+ if len(rows) > 5:
97
+ return random.sample(rows, 5)
98
+ return rows
99
+ except Exception as e:
100
+ return [["Error", str(e)]]
101
+
102
+ # ===================== PARSERS & AI GRADING =====================
103
+
104
+ def parse_txt_files():
105
+ try:
106
+ with open(PASSAGE_TXT, "r", encoding="utf-8") as f: p_lines = f.readlines()
107
+ with open(QUESTION_TXT, "r", encoding="utf-8") as f: q_lines = f.readlines()
108
 
109
+ # Simple passage parser
110
+ passages = {}
111
+ curr = 1; passages[curr] = []
112
+ for l in p_lines:
113
+ if "passage -" in l.lower():
114
+ curr = int(re.search(r'\d+', l).group()); passages[curr] = []
115
+ else: passages[curr].append(l)
116
 
117
+ # Simple question parser
118
+ qsets = {}
119
+ curr = 1; qsets[curr] = []
120
+ for l in q_lines:
121
+ if "question set" in l.lower():
122
+ curr = int(re.search(r'\d+', l).group()); qsets[curr] = []
123
+ elif l.strip(): qsets[curr].append(l.strip())
124
+
125
+ return [{"title": f"Story {i}", "passage": "".join(passages[i]).strip(), "questions": qsets[i]}
126
+ for i in sorted(set(passages) & set(qsets))]
127
+ except: return []
128
+
129
+ def run_grading(passage, qas):
130
+ client = OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL) if DEEPSEEK_API_KEY else OpenAI(api_key=OPENAI_API_KEY)
131
+ prompt = f"Grade these reading comprehension answers based on the passage. Judge factual accuracy only. Return JSON: {{'correct_count': int, 'details': [{{'question':str, 'is_correct':bool, 'reason':str}}]}}\nPassage: {passage}\nQA: {json.dumps(qas)}"
132
+ try:
133
+ r = client.chat.completions.create(model=DEEPSEEK_MODEL if DEEPSEEK_API_KEY else OPENAI_MODEL,
134
+ messages=[{"role":"user", "content":prompt}], temperature=0)
135
+ content = r.choices[0].message.content
136
+ if "```json" in content: content = content.split("```json")[1].split("```")[0]
137
+ return json.loads(content)
138
+ except Exception as e:
139
+ return {"correct_count": 0, "details": [], "error": str(e)}
140
+
141
+ # ===================== GRADIO UI =====================
142
+
143
+ with gr.Blocks(theme=gr.themes.Soft(), title="Vocab Master Reading") as demo:
144
+ # --- States ---
145
+ stories_state = gr.State(parse_txt_files())
146
+ s_idx = gr.State(0)
147
+ q_idx = gr.State(0)
148
+ ans_list_state = gr.State([])
149
+ gw_words_state = gr.State([])
150
+ start_time_state = gr.State(0)
151
+ timer_active = gr.State(False)
152
+
153
+ gr.Markdown("# 🏆 Vocab Master: Advanced Reading Comprehension")
154
+
155
+ # --- Section: Login ---
156
+ with gr.Row() as login_row:
157
+ name_in = gr.Textbox(label="Full Name", placeholder="Rajarshi Dasgupta")
158
+ class_in = gr.Dropdown(label="Class", choices=[str(i) for i in range(1, 11)])
159
+ btn_enter = gr.Button("Enter Module", variant="primary")
160
+
161
+ # --- Section: Gateway ---
162
+ with gr.Column(visible=False) as gateway_col:
163
+ gr.Markdown("### 🚪 Vocabulary Gateway\nExplain these 5 words to unlock today's story.")
164
+ gw_inputs = [gr.Textbox(label="Word", visible=False) for _ in range(5)]
165
+ btn_gw_submit = gr.Button("Verify & Unlock Story")
166
+ gw_feedback = gr.Markdown()
167
+
168
+ # --- Section: Main Module ---
169
+ with gr.Column(visible=False) as main_col:
170
+ with gr.Row():
171
+ timer_display = gr.Markdown("## ⏳ Time Remaining: 45:00", elem_classes=["timer-box"])
172
+ stars_counter = gr.Markdown("## ⭐ Stars: 0")
173
 
174
+ story_title = gr.Markdown("### Story Title")
175
+ with gr.Row():
176
+ with gr.Column(scale=2):
177
+ passage_box = gr.Textbox(label="Passage", lines=15, interactive=False)
178
+ with gr.Column(scale=1):
179
+ q_text = gr.Markdown("#### Question 1")
180
+ user_ans = gr.Textbox(label="Your Answer", lines=4, placeholder="Write at least 5 words...")
181
+ btn_save = gr.Button("Save & Next Question", variant="primary")
182
+ btn_finish = gr.Button("Finish & Grade", variant="stop")
 
 
 
183
 
184
+ results_area = gr.Markdown()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
185
 
186
+ # --- Functions: Login & Gateway ---
187
+ def on_enter_click(name, klass):
188
+ if not name or not klass: return gr.update(), gr.update(), gr.update(), "Error: Missing Info", []
 
 
189
 
190
+ allowed, msg = check_direct_entry(name, klass)
191
+ if allowed:
192
+ # Skip Gateway
193
+ return gr.update(visible=False), gr.update(visible=False), gr.update(visible=True), time.time(), True, []
194
 
195
+ # Load Gateway
196
+ words = get_words_for_gateway(klass)
197
+ # Prepare visibility for the 5 textboxes
198
+ updates = [gr.update(label=f"Define: {w[0]}", visible=True, value="") for w in words]
199
+ return gr.update(visible=False), gr.update(visible=True), gr.update(visible=False), 0, False, words, *updates
200
+
201
+ btn_enter.click(on_enter_click, [name_in, class_in],
202
+ [login_row, gateway_col, main_col, start_time_state, timer_active, gw_words_state] + gw_inputs)
203
+
204
+ def on_gw_verify(name, klass, words, *ans):
205
+ correct = sum(1 for a in ans if len(a.strip()) >= 3) # Simple length-based check for gateway
206
+ if correct >= 4:
207
+ return gr.update(visible=False), gr.update(visible=True), True, time.time(), ""
208
+ return gr.update(), gr.update(), False, 0, f"❌ Gateway Failed. You explained {correct}/5 words correctly. Need 4."
209
+
210
+ btn_gw_submit.click(on_gw_verify, [name_in, class_in, gw_words_state] + gw_inputs,
211
+ [gateway_col, main_col, timer_active, start_time_state, gw_feedback])
212
+
213
+ # --- Functions: Timer ---
214
+ def update_timer_ui(st, active):
215
+ if not active: return gr.update()
216
+ elapsed = time.time() - st
217
+ remaining = (QUIZ_LIMIT_MINUTES * 60) - elapsed
218
+ if remaining <= 0:
219
+ return "## 🛑 TIME EXPIRED! Module Locked."
220
+ mins, secs = divmod(int(remaining), 60)
221
+ return f"## ⏳ Time Remaining: {mins:02d}:{secs:02d}"
222
+
223
+ timer_obj = gr.Timer(1)
224
+ timer_obj.tick(update_timer_ui, [start_time_state, timer_active], [timer_display])
225
+
226
+ # --- Functions: Story Flow ---
227
+ def start_story(stories, si):
228
+ if not stories: return "No Story", "None", "Waiting..."
229
+ s = stories[si]
230
+ return f"### {s['title']}", s['passage'], f"**Question 1:** {s['questions'][0]}"
231
+
232
+ demo.load(start_story, [stories_state, s_idx], [story_title, passage_box, q_text])
233
+
234
+ def handle_save(si, qi, ans_list, current_ans, stories):
235
+ if len(current_ans.split()) < MIN_WORDS:
236
+ return qi, ans_list, gr.update(), f"⚠️ Please write at least {MIN_WORDS} words."
237
 
238
+ ans_list.append(current_ans)
239
+ new_qi = qi + 1
240
+ if new_qi < len(stories[si]['questions']):
241
+ return new_qi, ans_list, "", f"**Question {new_qi+1}:** {stories[si]['questions'][new_qi]}"
242
+ return qi, ans_list, "", "✅ All questions answered. Click 'Finish & Grade'."
243
+
244
+ btn_save.click(handle_save, [s_idx, q_idx, ans_list_state, user_ans, stories_state],
245
+ [q_idx, ans_list_state, user_ans, q_text])
246
+
247
+ def handle_finish(si, ans_list, last_ans, name, klass, stories, active_time):
248
+ if not active_time: return "Module is locked."
249
+ if last_ans: ans_list.append(last_ans)
250
 
251
+ story = stories[si]
252
+ qas = list(zip(story['questions'], ans_list))
253
+
254
+ # AI Grading
255
+ result = run_grading(story['passage'], qas)
256
+ count = result.get('correct_count', 0)
257
+ perc = (count / len(story['questions'])) * 100
258
+ stars = 5 if perc >= 90 else 4 if perc >= 80 else 3 if perc >= 70 else 2 if perc >= 60 else 1 if perc >= 50 else 0
259
+
260
+ # Save to Google Sheets
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
261
  try:
262
+ gc = get_gspread_client()
263
+ sh = gc.open_by_key(SHEETS_SPREADSHEET_ID).worksheet("Scores")
264
+ sh.append_row([
265
+ datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S"),
266
+ name, klass, count, len(story['questions']), f"{int(perc)}%", stars, "Comprehension--Reading"
267
+ ])
268
+ except: pass
269
+
270
+ # Build Feedback UI
271
+ report = f"## Results for {name}\n**Score:** {int(perc)}% | **Stars:** {'⭐' * stars}\n\n"
272
+ for d in result.get('details', []):
273
+ mark = "✅" if d['is_correct'] else "❌"
274
+ report += f"{mark} **Q:** {d['question']}\n - *Feedback:* {d.get('reason', 'N/A')}\n\n"
275
+
276
+ return report
277
+
278
+ btn_finish.click(handle_finish, [s_idx, ans_list_state, user_ans, name_in, class_in, stories_state, timer_active], [results_area])
 
 
 
 
 
 
 
 
 
279
 
280
  if __name__ == "__main__":
281
+ demo.launch()