Spaces:
Sleeping
Sleeping
Download app.py from SingerkoneRKM/comprehensiongrader: direct link, hf CLI and curl.
- Browser
- Download file 36.1 kB
-
https://huggingface.co/spaces/SingerkoneRKM/comprehensiongrader/resolve/main/app.py
- Command line
-
hf download hf://spaces/SingerkoneRKM/comprehensiongrader/app.py
-
curl -L -o app.py https://huggingface.co/spaces/SingerkoneRKM/comprehensiongrader/resolve/main/app.py
36.1 kB
| """ | |
| ADAPTIVE READING COMPREHENSION β v6 | |
| ===================================== | |
| Changes vs v5: | |
| 1. Login now takes ROLL NUMBER + PASSWORD instead of free-text Name/Class. | |
| 2. Name + Class are reverse-looked-up from the gateway sheet: | |
| https://docs.google.com/spreadsheets/d/1jjxLQED9tJKKMd5yIlQfpxc7dxsLkqB22Vf5ZYKeAio | |
| (worksheet "name roll", columns: Name | Class | Roll | Password | year | status(pass/fail)) | |
| 3. Effective class = sheet Class + (current_year - sheet year), i.e. the | |
| student is auto-promoted one class per year that has passed since the | |
| sheet's `year` value β UNLESS status(pass/fail) says "fail", in which | |
| case no promotion happens (student repeats the same class). | |
| Example: sheet says year=2026, Class=6, status=pass. In 2027, the | |
| student is treated as Class 7. If status had been "fail", they'd | |
| stay Class 6 in 2027. | |
| 4. Name + (promoted) Class are what get saved to the Scores sheet, exactly | |
| as before (Date | Name | Classs | Result | Full Marks | Percentage | | |
| Star | Level | ...). | |
| Files needed: pssg1.txt qstn1.txt previous.txt (optional) | |
| Secrets: DEEPSEEK_API_KEY gcp_service_account | |
| """ | |
| import os, re, json, time, datetime | |
| import gradio as gr | |
| BASE_DIR = os.path.dirname(os.path.abspath(__file__)) | |
| MAX_QUESTIONS = 6 | |
| THRESHOLD_STAR = 4 | |
| LOW_STAR_LIMIT = 2 | |
| DEEPSEEK_API_KEY = os.getenv("DEEPSEEK_API_KEY") | |
| DEEPSEEK_BASE_URL = "https://api.deepseek.com" | |
| DEEPSEEK_MODEL = "deepseek-v4-pro" | |
| SPREADSHEET_ID = "18oKXXwKMWE_CfKJGljWqRAKAIsp0SK6ffmkly2GHnxk" | |
| WORKSHEET_NAME = "Scores" | |
| # Gateway sheet β reverse-map Roll+Password -> Name / Class / year / status | |
| GATEWAY_SHEET_ID = "1jjxLQED9tJKKMd5yIlQfpxc7dxsLkqB22Vf5ZYKeAio" | |
| GATEWAY_WORKSHEET_NAME = "name roll" | |
| HIDE_DELAY = [(i + 1) * 5 for i in range(MAX_QUESTIONS)] # 5,10,15,20,25,30s | |
| # ============================================================= | |
| # LAZY CLIENTS | |
| # ============================================================= | |
| def get_llm_client(): | |
| if not DEEPSEEK_API_KEY: return None | |
| try: | |
| from openai import OpenAI | |
| return OpenAI(api_key=DEEPSEEK_API_KEY, base_url=DEEPSEEK_BASE_URL) | |
| except Exception as e: | |
| print(f"[LLM] {e}"); return None | |
| def _gspread_client(): | |
| try: | |
| import gspread | |
| from google.oauth2.service_account import Credentials | |
| except ImportError as e: | |
| raise RuntimeError(f"pip install gspread google-auth ({e})") | |
| raw = os.environ.get("gcp_service_account") | |
| if not raw: raise RuntimeError("gcp_service_account secret not set") | |
| creds = Credentials.from_service_account_info( | |
| json.loads(raw), | |
| scopes=["https://www.googleapis.com/auth/spreadsheets"]) | |
| return gspread.authorize(creds) | |
| def get_sheet(): | |
| return _gspread_client().open_by_key(SPREADSHEET_ID).worksheet(WORKSHEET_NAME) | |
| def get_gateway_sheet(): | |
| return _gspread_client().open_by_key(GATEWAY_SHEET_ID).worksheet(GATEWAY_WORKSHEET_NAME) | |
| # ============================================================= | |
| # GOOGLE SHEETS β SCORES | |
| # Columns: Date | Name | Classs | Result | Full Marks | Percentage | Star | Level | |
| # ============================================================= | |
| def log_to_sheets(name, grade, result, full_marks, percent, stars, level_label): | |
| try: | |
| row = [datetime.datetime.now().strftime("%m/%d/%Y %H:%M:%S"), | |
| name, grade, result, full_marks, | |
| round(float(percent), 1), stars, level_label] | |
| get_sheet().append_row(row, value_input_option="USER_ENTERED") | |
| print(f"[Sheets] saved {name} stars={stars} level={level_label}") | |
| return "" | |
| except Exception as e: | |
| import traceback; traceback.print_exc() | |
| return f"{type(e).__name__}: {e}" | |
| # ============================================================= | |
| # STUDENT LOGIN β GATEWAY SHEET (Roll + Password -> Name / Class) | |
| # ============================================================= | |
| def lookup_student(roll, password): | |
| """ | |
| Look up a student by Roll + Password in the gateway sheet. | |
| Returns (record_dict, "") on success, or (None, error_message) on failure. | |
| record_dict = {"name": str, "class": str, "year": value, "status": str} | |
| """ | |
| try: | |
| ws = get_gateway_sheet() | |
| records = ws.get_all_records() | |
| except Exception as e: | |
| return None, f"Could not reach the student database: {type(e).__name__}: {e}" | |
| roll_clean = str(roll).strip() | |
| pwd_clean = str(password).strip() | |
| for row in records: | |
| sheet_roll = str(row.get("Roll", "")).strip() | |
| if sheet_roll.lower() == roll_clean.lower(): | |
| sheet_pwd = str(row.get("Password", "")).strip() | |
| if sheet_pwd != pwd_clean: | |
| return None, "Incorrect password." | |
| return { | |
| "name": str(row.get("Name", "")).strip(), | |
| "class": str(row.get("Class", "")).strip(), | |
| "year": row.get("year", ""), | |
| "status": str(row.get("status(pass/fail)", "")).strip(), | |
| }, "" | |
| return None, "Roll number not found." | |
| def compute_effective_class(base_class, sheet_year, status): | |
| """ | |
| Promote the sheet's Class by one for every year that has passed since | |
| `sheet_year`, unless `status` marks the student as having failed (in | |
| which case they stay at the same class β no promotion). | |
| """ | |
| m = re.match(r"(\d+)", str(base_class).strip()) | |
| if not m: | |
| return str(base_class).strip() # non-numeric class, leave as-is | |
| base_num = int(m.group(1)) | |
| try: | |
| sheet_year_num = int(str(sheet_year).strip()) | |
| except (TypeError, ValueError): | |
| return str(base_num) # no usable year, no promotion | |
| current_year = datetime.datetime.now().year | |
| years_passed = max(0, current_year - sheet_year_num) | |
| failed = str(status).strip().lower().startswith("fail") | |
| if failed: | |
| years_passed = 0 | |
| return str(base_num + years_passed) | |
| # ============================================================= | |
| # FILE LOADING | |
| # ============================================================= | |
| def is_class5(klass: str) -> bool: | |
| return str(klass).strip().startswith("5") | |
| def load_passages_and_questions(klass: str): | |
| passages, questions = {}, {} | |
| class5 = is_class5(klass) | |
| for fname in os.listdir(BASE_DIR): | |
| # ================= PASSAGES ================= | |
| if class5: | |
| m = re.match(r'pssg(\d+)class5\.txt$', fname) | |
| else: | |
| m = re.match(r'pssg(\d+)\.txt$', fname) | |
| if m: | |
| idx = int(m.group(1)) | |
| passages[idx] = open( | |
| os.path.join(BASE_DIR, fname), | |
| encoding="utf-8" | |
| ).read().strip() | |
| # ================= QUESTIONS ================= | |
| if class5: | |
| m = re.match(r'(?:qstn|question)(\d+)class5\.txt$', fname) | |
| else: | |
| m = re.match(r'(?:qstn|question)(\d+)\.txt$', fname) | |
| if m: | |
| idx = int(m.group(1)) | |
| questions[idx] = [ | |
| l.strip() for l in open( | |
| os.path.join(BASE_DIR, fname), | |
| encoding="utf-8" | |
| ) if l.strip() | |
| ] | |
| return passages, questions | |
| def load_previous(): | |
| p = os.path.join(BASE_DIR, "previous.txt") | |
| return (open(p, encoding="utf-8").read().strip() | |
| if os.path.exists(p) | |
| else "No previous.txt found.") | |
| # ============================================================= | |
| # STARS / LEVEL | |
| # ============================================================= | |
| def passages_for_level(level): | |
| # Level -1 β 2 passages, 0 β 3, 1 β 4, 2 β 5 β¦ (capped at 8) | |
| return min(8, max(2, level + 3)) | |
| def pass1_stars_from_score(correct, total): | |
| # 0-5 stars from meaning only | |
| if total <= 0 or correct <= 0: return 0 | |
| if correct >= total: return 5 | |
| return max(1, round(correct / total * 5)) | |
| def english_bonus(eng_correct, eng_total, mode): | |
| if eng_total <= 0: return 0 | |
| ratio = eng_correct / eng_total | |
| max_b = 3 if mode == "disappearing" else 1 | |
| return round(ratio * max_b) | |
| def compute_next_level(current, stars): | |
| if stars >= THRESHOLD_STAR: return current + 1 | |
| if stars <= LOW_STAR_LIMIT: return max(-1, current - 1) # floor at -1 | |
| return current | |
| def stars_display(n): | |
| n = max(0, min(8, int(round(n)))) | |
| return "β" * n + "β" * max(0, 8 - n) | |
| def build_level_label(level, mode): | |
| return f"Comprehension-Level {level} - {mode}" | |
| # ============================================================= | |
| # LLM β PASS 1 | |
| # ============================================================= | |
| def grade_answers(passage, questions, answers): | |
| client = get_llm_client() | |
| if not client: return _fallback_grade(questions, answers) | |
| lines = [] | |
| for i,(q,a) in enumerate(zip(questions,answers)): | |
| if not q.strip(): continue | |
| ans_text = a.strip() if a.strip() else "[NO ANSWER β mark as 0, incorrect]" | |
| lines.append(f"Q{i+1}: {q}\nA{i+1}: {ans_text}") | |
| qa = "\n".join(lines) | |
| sys_p = ("Grade reading-comp answers on meaning only. Spelling OK. " | |
| "STRICT RULE: Any answer marked [NO ANSWER] must receive 0 credit and " | |
| "be marked incorrect. Do not infer or assume any answer. " | |
| "Partial credit allowed for partial answers. " | |
| "Return ONLY JSON: correct_count(float), total_questions(int), " | |
| "percent(float 0-100), feedback(list of strings, one per active question).") | |
| try: | |
| r = client.chat.completions.create( | |
| model=DEEPSEEK_MODEL, temperature=0, | |
| messages=[{"role":"system","content":sys_p}, | |
| {"role":"user", | |
| "content":f"PASSAGE:\n{passage}\n\nQ&A:\n{qa}\n\nJSON only."}]) | |
| raw = re.sub(r"^```[a-z]*\n?","",r.choices[0].message.content.strip()) | |
| return json.loads(re.sub(r"\n?```$","",raw)) | |
| except Exception as e: | |
| print(f"[P1] {e}"); return _fallback_grade(questions, answers) | |
| def _fallback_grade(questions, answers): | |
| total = sum(1 for q in questions if q.strip()) | |
| answered = sum(1 for q,a in zip(questions,answers) if q.strip() and a.strip()) | |
| return {"correct_count": answered, "total_questions": total, | |
| "percent": round(answered/total*100 if total else 0), | |
| "feedback": ["(No LLM)"] * total} | |
| # ============================================================= | |
| # LLM β MODEL ANSWERS | |
| # ============================================================= | |
| def get_model_answers(passage, questions): | |
| client = get_llm_client() | |
| active = [q for q in questions if q.strip()] | |
| if not client: return ["(unavailable)"] * len(active) | |
| q_block = "\n".join(f"Q{i+1}: {q}" for i,q in enumerate(questions) if q.strip()) | |
| sys_p = ("One concise, grammatically correct English sentence per question. " | |
| "Return ONLY JSON: model_answers(list of strings).") | |
| try: | |
| r = client.chat.completions.create( | |
| model=DEEPSEEK_MODEL, temperature=0, | |
| messages=[{"role":"system","content":sys_p}, | |
| {"role":"user", | |
| "content":f"PASSAGE:\n{passage}\n\nQUESTIONS:\n{q_block}\n\nJSON only."}]) | |
| raw = re.sub(r"^```[a-z]*\n?","",r.choices[0].message.content.strip()) | |
| return json.loads(re.sub(r"\n?```$","",raw)).get("model_answers", [""]*len(active)) | |
| except Exception as e: | |
| print(f"[MA] {e}"); return ["(unavailable)"] * len(active) | |
| # ============================================================= | |
| # LLM β PASS 2 | |
| # ============================================================= | |
| def grade_english_rewrite(questions, model_answers, rewrites): | |
| client = get_llm_client() | |
| active = [q for q in questions if q.strip()] | |
| total = len(active) | |
| if not client: | |
| filled = sum(1 for a in rewrites if a.strip()) | |
| return {"correct_count": filled, "total": total, "feedback": ["(No LLM)"]*total} | |
| lines = [f"Q{i+1}: {q}\nModel: {ma}\nStudent: {rw}" | |
| for i,(q,ma,rw) in enumerate(zip(questions,model_answers,rewrites)) | |
| if q.strip()] | |
| sys_p = ("Check if each student rewrite is grammatically correct, complete, " | |
| "captures meaning. Ignore spaces; minor spelling OK; " | |
| "must start capital, end full stop. " | |
| "STRICT RULE: blank or missing rewrites must score 0 β do not give credit. " | |
| "Return ONLY JSON: correct_count(int), total(int), feedback(list).") | |
| try: | |
| r = client.chat.completions.create( | |
| model=DEEPSEEK_MODEL, temperature=0, | |
| messages=[{"role":"system","content":sys_p}, | |
| {"role":"user","content":"\n\n".join(lines)+"\n\nJSON only."}]) | |
| raw = re.sub(r"^```[a-z]*\n?","",r.choices[0].message.content.strip()) | |
| data = json.loads(re.sub(r"\n?```$","",raw)) | |
| return {"correct_count": data.get("correct_count",0), | |
| "total": data.get("total", total), | |
| "feedback": data.get("feedback",[])} | |
| except Exception as e: | |
| print(f"[P2] {e}") | |
| filled = sum(1 for a in rewrites if a.strip()) | |
| return {"correct_count": filled, "total": total, "feedback": [str(e)]*total} | |
| # ============================================================= | |
| # HTML HELPERS (no <script> β stripped by Gradio 5) | |
| # ============================================================= | |
| NS = ("user-select:none;-webkit-user-select:none;" | |
| "-moz-user-select:none;-ms-user-select:none;pointer-events:none;") | |
| def passage_html(text): | |
| if not text: return "" | |
| return (f'<div style="background:#fafafa;border:1px solid #ddd;' | |
| f'border-radius:6px;padding:16px;font-size:15px;line-height:1.8;{NS}">' | |
| f'{text.replace(chr(10),"<br>")}</div>') | |
| def ma_card_text(i, answer, mode): | |
| delay = HIDE_DELAY[i] | |
| note = f" *(hides in {delay}s)*" if mode == "disappearing" else "" | |
| return f"**Model Answer Q{i+1}{note}:** {answer}" | |
| ANTI_COPY = """<script> | |
| ['contextmenu','copy','cut'].forEach(e=> | |
| document.addEventListener(e,x=>x.preventDefault())); | |
| document.addEventListener('selectstart',x=>{ | |
| if(!['INPUT','TEXTAREA'].includes(x.target.tagName))x.preventDefault(); | |
| }); | |
| </script>""" | |
| # ============================================================= | |
| # SESSION STATE | |
| # ============================================================= | |
| def fresh_state(): | |
| return { | |
| "student_name":"","student_grade":"","text_mode":"disappearing", | |
| "level":0,"passages":{},"questions":{},"indices":[],"ptr":0, | |
| "round_num":0,"Pssg_end":"NO", | |
| "current_passage":"","current_questions":[], | |
| "model_answers_list":[], | |
| "ma_shown_at":None, | |
| "ma_hidden":[False]*MAX_QUESTIONS, | |
| "pass1_stars":0,"pass1_correct":0.0,"pass1_total":0,"pass1_percent":0.0, | |
| "cumulative_correct":0.0,"cumulative_total":0, | |
| "all_stars":[],"last_stars":0, | |
| } | |
| def load_next_chunk(state): | |
| size = passages_for_level(state["level"]) | |
| chunk = state["indices"][state["ptr"]: state["ptr"] + size] | |
| if not chunk: return False | |
| next_ptr = state["ptr"] + size | |
| state["Pssg_end"] = "YES" if next_ptr >= len(state["indices"]) else "NO" | |
| state["current_passage"] = "\n\n".join(state["passages"][i] for i in chunk) | |
| qs = [] | |
| for i in chunk: qs += state["questions"].get(i,[]) | |
| state["current_questions"] = qs[:MAX_QUESTIONS] | |
| state["model_answers_list"] = [] | |
| state["ma_shown_at"] = None | |
| state["ma_hidden"] = [False]*MAX_QUESTIONS | |
| state["ptr"] += size | |
| return True | |
| # ============================================================= | |
| # UI HELPERS | |
| # ============================================================= | |
| def q_updates(q_list, vis): | |
| return [gr.update(value=f"**Q{i+1}:** {q_list[i]}", visible=True) | |
| if vis and i < len(q_list) else gr.update(value="", visible=False) | |
| for i in range(MAX_QUESTIONS)] | |
| def a_updates(q_list, vis): | |
| return [gr.update(value="", visible=(vis and i < len(q_list))) | |
| for i in range(MAX_QUESTIONS)] | |
| def rw_updates(q_list, vis): | |
| return [gr.update(value="", visible=(vis and i < len(q_list)), | |
| label=f"Rewrite Q{i+1} in correct English") | |
| for i in range(MAX_QUESTIONS)] | |
| def ma_updates_show(q_list, model_answers, mode): | |
| out = [] | |
| for i in range(MAX_QUESTIONS): | |
| if i < len(q_list) and i < len(model_answers): | |
| out.append(gr.update(value=ma_card_text(i, model_answers[i], mode), | |
| visible=True)) | |
| else: | |
| out.append(gr.update(value="", visible=False)) | |
| return out | |
| def ma_updates_hide(): | |
| return [gr.update(value="", visible=False) for _ in range(MAX_QUESTIONS)] | |
| # ============================================================= | |
| # BUILD UI | |
| # ============================================================= | |
| with gr.Blocks(title="Reading Comprehension Quiz", theme=gr.themes.Soft()) as demo: | |
| gr.HTML(ANTI_COPY) | |
| gr.Markdown("# π Adaptive Reading Comprehension Quiz") | |
| # ββ WELCOME ββββββββββββββββββββββββββββββββββββββββββββ | |
| with gr.Group(visible=True) as welcome_panel: | |
| gr.Markdown("## Step 1 β Choose how model answers are shown") | |
| gr.Markdown( | |
| "| Mode | How it works | Bonus stars |\n" | |
| "|---|---|---|\n" | |
| "| β±οΈ **Disappearing** | Q1 vanishes after 5s, Q2 after 10s β¦ | Up to **+3** |\n" | |
| "| π **Static** | Answers stay on screen | Up to **+1** |" | |
| ) | |
| with gr.Row(): | |
| btn_dis = gr.Button("β±οΈ Disappearing (harder)", variant="primary", size="lg") | |
| btn_sta = gr.Button("π Static (easier)", variant="secondary", size="lg") | |
| mode_state = gr.State("disappearing") | |
| chosen_md = gr.Markdown( | |
| "> β **Disappearing** selected β answers vanish one by one. " | |
| "Earn up to **+3 bonus stars**.") | |
| def pick_dis(_): | |
| return ("disappearing", | |
| "> β **Disappearing** selected β answers vanish one by one. " | |
| "Earn up to **+3 bonus stars**.", | |
| gr.update(variant="primary"), gr.update(variant="secondary")) | |
| def pick_sta(_): | |
| return ("static", | |
| "> β **Static** selected β answers stay on screen. " | |
| "Earn up to **+1 bonus star**.", | |
| gr.update(variant="secondary"), gr.update(variant="primary")) | |
| btn_dis.click(pick_dis, inputs=[mode_state], | |
| outputs=[mode_state, chosen_md, btn_dis, btn_sta]) | |
| btn_sta.click(pick_sta, inputs=[mode_state], | |
| outputs=[mode_state, chosen_md, btn_dis, btn_sta]) | |
| gr.Markdown("---") | |
| gr.Markdown( | |
| "### π How the quiz works\n" | |
| "1. Read the passage β **you cannot copy it**.\n" | |
| "2. Answer questions and click **Submit Answers** (Pass 1 β graded on meaning, 0-5 stars).\n" | |
| "3. Model answers appear β study them, then rewrite in correct English (Pass 2 β bonus stars).\n" | |
| "4. Score high (4+ stars) β harder next passage. Score low (0-2) β easier.\n" | |
| "5. Your final score is **saved only after all passages are complete**." | |
| ) | |
| gr.Markdown("---") | |
| btn_past = gr.Button("π View Past Story", variant="secondary") | |
| past_story = gr.Markdown(visible=False) | |
| btn_past.click( | |
| lambda: gr.update(value=load_previous(), visible=True), | |
| outputs=[past_story]) | |
| gr.Markdown("---") | |
| gr.Markdown("## Step 2 β Enter your Roll Number and Password") | |
| inp_roll = gr.Textbox(label="Roll Number", placeholder="e.g. SK-2026-6015") | |
| inp_pwd = gr.Textbox(label="Password", placeholder="Your password", type="password") | |
| login_err = gr.Markdown("") | |
| btn_start = gr.Button("βΆ Start Quiz", variant="primary", size="lg") | |
| # ββ QUIZ βββββββββββββββββββββββββββββββββββββββββββββββ | |
| with gr.Group(visible=False) as quiz_panel: | |
| status_md = gr.Markdown("### Level 0") | |
| passage_box = gr.HTML("") | |
| gr.Markdown("---") | |
| gr.Markdown("#### βοΈ Your answers") | |
| q_labels = [gr.Markdown(visible=False) for _ in range(MAX_QUESTIONS)] | |
| a_boxes = [gr.Textbox(label=f"Answer {i+1}", visible=False, lines=2) | |
| for i in range(MAX_QUESTIONS)] | |
| thinking_md = gr.Markdown(visible=False) | |
| btn_submit = gr.Button("β Submit Answers", variant="primary") | |
| result_md = gr.Markdown("") | |
| # Individual model-answer cards (one per question) | |
| # These are hidden/shown by the Timer | |
| gr.Markdown("---") | |
| rewrite_hdr = gr.Markdown(visible=False) | |
| ma_cards = [gr.Markdown(visible=False) for _ in range(MAX_QUESTIONS)] | |
| gr.Markdown("---") | |
| rw_boxes = [gr.Textbox(label=f"Rewrite Q{i+1} in correct English", | |
| visible=False, lines=2) | |
| for i in range(MAX_QUESTIONS)] | |
| thinking2_md = gr.Markdown(visible=False) | |
| btn_submit_rw = gr.Button("β Submit Rewrite", variant="primary", visible=False) | |
| result2_md = gr.Markdown("") | |
| btn_next = gr.Button("β‘ Next Passage", visible=False) | |
| # ββ DONE βββββββββββββββββββββββββββββββββββββββββββββββ | |
| with gr.Group(visible=False) as done_panel: | |
| gr.Markdown("## Quiz Complete!") | |
| done_md = gr.Markdown("") | |
| sess = gr.State(fresh_state()) | |
| # Separate state for timer β prevents Timer tick from overwriting main sess | |
| ma_timer_state = gr.State({"shown_at": None, "hidden": [False]*MAX_QUESTIONS, "mode": "disappearing"}) | |
| # ββ TIMER β hides model-answer cards one by one βββββββββ | |
| try: | |
| tick = gr.Timer(value=1) | |
| def cb_tick(ts): | |
| # ts keys: shown_at / hidden / mode (separate from main sess) | |
| no_change = (ts, *([gr.update()] * MAX_QUESTIONS)) | |
| if ts.get("shown_at") is None: | |
| return no_change | |
| if ts.get("mode") != "disappearing": | |
| return no_change | |
| elapsed = time.time() - ts["shown_at"] | |
| updates = [] | |
| for i in range(MAX_QUESTIONS): | |
| if ts["hidden"][i]: | |
| updates.append(gr.update()) # already hidden | |
| elif elapsed >= HIDE_DELAY[i]: | |
| ts["hidden"][i] = True | |
| updates.append(gr.update( | |
| value=f"~~Q{i+1} model answer β time is up~~", | |
| visible=True)) | |
| else: | |
| updates.append(gr.update()) # still visible, no change | |
| return (ts, *updates) | |
| tick.tick(cb_tick, inputs=[ma_timer_state], outputs=[ma_timer_state, *ma_cards]) | |
| except AttributeError: | |
| pass | |
| # ========================================================== | |
| # START β now looks up Name + Class from Roll + Password | |
| # ========================================================== | |
| def cb_start(roll, pwd, mode, state): | |
| fail_ret = (state, | |
| gr.update(), gr.update(), gr.update(), "", | |
| "", "", | |
| *q_updates([], False), *a_updates([], False), | |
| gr.update(visible=False), gr.update(visible=True), | |
| *ma_updates_hide(), | |
| gr.update(visible=False), *rw_updates([], False), | |
| gr.update(visible=False), "", "", | |
| gr.update(visible=False)) | |
| if not roll.strip() or not pwd.strip(): | |
| ret = list(fail_ret) | |
| ret[4] = "Please enter your roll number and password." | |
| return tuple(ret) | |
| record, err = lookup_student(roll, pwd) | |
| if record is None: | |
| ret = list(fail_ret) | |
| ret[4] = err or "Login failed." | |
| return tuple(ret) | |
| name = record["name"] | |
| eff_class = compute_effective_class(record["class"], record["year"], record["status"]) | |
| passages, qs = load_passages_and_questions(eff_class) | |
| if not passages: | |
| ret = list(fail_ret) | |
| ret[4] = f"No passage files found for Class {eff_class}." | |
| return tuple(ret) | |
| state.update({ | |
| "student_name": name, "student_grade": eff_class, | |
| "text_mode": mode, "passages": passages, "questions": qs, | |
| "indices": sorted(passages.keys()), | |
| }) | |
| if not load_next_chunk(state): | |
| ret = list(fail_ret) | |
| ret[4] = "No passages available." | |
| return tuple(ret) | |
| total = len(state["indices"]) | |
| return ( | |
| state, | |
| gr.update(visible=False), # welcome | |
| gr.update(visible=True), # quiz | |
| gr.update(visible=False), # done | |
| "", | |
| f"### {name} | Class {eff_class} | Level {state['level']} | Passage 1 of {total}", | |
| passage_html(state["current_passage"]), | |
| *q_updates(state["current_questions"], True), | |
| *a_updates(state["current_questions"], True), | |
| gr.update(visible=False), # thinking_md | |
| gr.update(visible=True), # btn_submit | |
| *ma_updates_hide(), | |
| gr.update(visible=False), # rewrite_hdr | |
| *rw_updates([], False), | |
| gr.update(visible=False), # btn_submit_rw | |
| "", "", | |
| gr.update(visible=False), # btn_next | |
| ) | |
| btn_start.click( | |
| cb_start, | |
| inputs=[inp_roll, inp_pwd, mode_state, sess], | |
| outputs=[ | |
| sess, | |
| welcome_panel, quiz_panel, done_panel, | |
| login_err, | |
| status_md, passage_box, | |
| *q_labels, *a_boxes, | |
| thinking_md, btn_submit, | |
| *ma_cards, | |
| rewrite_hdr, *rw_boxes, | |
| btn_submit_rw, | |
| result_md, result2_md, | |
| btn_next, | |
| ], | |
| ) | |
| # ========================================================== | |
| # SUBMIT P1 β step A: show spinner | |
| # ========================================================== | |
| def show_p1_spinner(state): | |
| return (gr.update(value="Ⳡ**Grading your answers⦠please wait.**", | |
| visible=True), | |
| gr.update(visible=False)) | |
| def cb_submit(state, *answer_vals): | |
| answers = list(answer_vals) | |
| questions = state["current_questions"] | |
| mode = state["text_mode"] | |
| result = grade_answers(state["current_passage"], questions, answers) | |
| percent = result.get("percent", 0) | |
| correct_count = result.get("correct_count", 0) | |
| total_q = result.get("total_questions", len(questions)) | |
| feedback = result.get("feedback", []) | |
| p1_stars = pass1_stars_from_score(correct_count, total_q) | |
| state["pass1_stars"] = p1_stars | |
| state["pass1_correct"] = correct_count | |
| state["pass1_total"] = total_q | |
| state["pass1_percent"] = percent | |
| state["cumulative_correct"] = state.get("cumulative_correct",0) + correct_count | |
| state["cumulative_total"] = state.get("cumulative_total", 0) + total_q | |
| fb_lines = [f"- **Q{i+1}:** {feedback[i] if i<len(feedback) else ''}" | |
| for i,q in enumerate(questions) if q.strip()] | |
| max_b = 3 if mode == "disappearing" else 1 | |
| result_text = ( | |
| f"### Pass 1 β Meaning\n" | |
| f"**Score:** {correct_count}/{total_q} ({percent:.0f}%)\n\n" | |
| f"**Stars:** {stars_display(p1_stars)} ({p1_stars} / 5)\n\n" | |
| + "\n".join(fb_lines) + "\n\n" | |
| + f"*Study the model answers below. Rewrite in correct English " | |
| f"to earn up to **+{max_b} bonus stars**.*" | |
| ) | |
| model_answers = get_model_answers(state["current_passage"], questions) | |
| state["model_answers_list"] = model_answers | |
| state["ma_shown_at"] = time.time() | |
| state["ma_hidden"] = [False] * MAX_QUESTIONS | |
| mode_label = ("β±οΈ Answers disappear one by one β rewrite quickly!" | |
| if mode == "disappearing" | |
| else "π Answers stay on screen β rewrite in correct English below.") | |
| rw_hdr = f"#### π Model Answers β {mode_label}" | |
| # Build updated timer state for the separate timer gr.State | |
| new_timer_state = { | |
| "shown_at": state["ma_shown_at"], | |
| "hidden": list(state["ma_hidden"]), | |
| "mode": mode, | |
| } | |
| return ( | |
| state, | |
| new_timer_state, # ma_timer_state | |
| gr.update(visible=False), # thinking_md | |
| result_text, | |
| gr.update(value=rw_hdr, visible=True), # rewrite_hdr | |
| *ma_updates_show(questions, model_answers, mode), # ma_cards | |
| *rw_updates(questions, True), # rw_boxes | |
| gr.update(visible=True), # btn_submit_rw | |
| ) | |
| btn_submit.click( | |
| show_p1_spinner, | |
| inputs=[sess], | |
| outputs=[thinking_md, btn_submit], | |
| ).then( | |
| cb_submit, | |
| inputs=[sess, *a_boxes], | |
| outputs=[ | |
| sess, ma_timer_state, thinking_md, result_md, | |
| rewrite_hdr, | |
| *ma_cards, | |
| *rw_boxes, | |
| btn_submit_rw, | |
| ], | |
| ) | |
| # ========================================================== | |
| # SUBMIT P2 β step A: show spinner | |
| # ========================================================== | |
| def show_p2_spinner(state): | |
| return (gr.update(value="Ⳡ**Checking your English⦠please wait.**", | |
| visible=True), | |
| gr.update(visible=False)) | |
| def cb_submit_rewrite(state, *rw_vals): | |
| rewrites = list(rw_vals) | |
| questions = state["current_questions"] | |
| mode = state["text_mode"] | |
| eng = grade_english_rewrite(questions, state["model_answers_list"], rewrites) | |
| eng_corr = eng.get("correct_count", 0) | |
| eng_total = eng.get("total", len([q for q in questions if q.strip()])) | |
| eng_fb = eng.get("feedback", []) | |
| bonus = english_bonus(eng_corr, eng_total, mode) | |
| final_stars = min(8, state["pass1_stars"] + bonus) | |
| state["last_stars"] = final_stars | |
| state["round_num"] += 1 | |
| state["all_stars"].append(final_stars) | |
| avg = (round(sum(state["all_stars"])/len(state["all_stars"]),2) | |
| if state["all_stars"] else 0) | |
| max_b = 3 if mode == "disappearing" else 1 | |
| bonus_line = ( | |
| f"Earned **+{bonus}** bonus star{'s' if bonus!=1 else ''} " | |
| f"({eng_corr}/{eng_total} rewrites correct)" | |
| if bonus > 0 | |
| else f"No bonus this time β {eng_corr}/{eng_total} rewrites met the standard." | |
| ) | |
| eng_fb_lines = [f"- **Q{i+1}:** {eng_fb[i] if i<len(eng_fb) else ''}" | |
| for i,q in enumerate(questions) if q.strip()] | |
| sheets_status = "" | |
| if state["Pssg_end"] == "YES": | |
| cc = state.get("cumulative_correct", 0) | |
| ct = state.get("cumulative_total", 0) | |
| pct = round(cc/ct*100 if ct else 0, 1) | |
| avg_s = round(sum(state["all_stars"])/len(state["all_stars"]),2) \ | |
| if state["all_stars"] else 0 | |
| err = log_to_sheets( | |
| state["student_name"], state["student_grade"], | |
| round(cc,1), ct, pct, | |
| round(avg_s,2), | |
| build_level_label(state["level"], mode) | |
| ) | |
| sheets_status = ( | |
| "\n\n**Score saved to Google Sheets.**" | |
| if not err else f"\n\nSheets error: `{err}`" | |
| ) | |
| result2_text = ( | |
| f"### Pass 2 β English Quality\n" | |
| f"**Rewrites correct:** {eng_corr}/{eng_total}\n\n" | |
| f"{bonus_line}\n\n" | |
| f"**Final Stars:** {stars_display(final_stars)} " | |
| f"({final_stars} / 8) " | |
| f"*(Pass 1: {state['pass1_stars']}/5 + Bonus: +{bonus})*\n\n" | |
| f"**Running average:** {avg:.2f} / 8\n\n" | |
| + "\n".join(eng_fb_lines) | |
| + sheets_status | |
| ) | |
| more = state["ptr"] < len(state["indices"]) | |
| return ( | |
| state, | |
| gr.update(visible=False), # thinking2_md | |
| result2_text, | |
| gr.update(visible=False), # btn_submit_rw | |
| gr.update(visible=more), # btn_next | |
| ) | |
| btn_submit_rw.click( | |
| show_p2_spinner, | |
| inputs=[sess], | |
| outputs=[thinking2_md, btn_submit_rw], | |
| ).then( | |
| cb_submit_rewrite, | |
| inputs=[sess, *rw_boxes], | |
| outputs=[sess, thinking2_md, result2_md, btn_submit_rw, btn_next], | |
| ) | |
| # ========================================================== | |
| # NEXT | |
| # ========================================================== | |
| def cb_next(state): | |
| state["level"] = compute_next_level(state["level"], state["last_stars"]) | |
| ok = load_next_chunk(state) | |
| if not ok: | |
| avg = (round(sum(state["all_stars"])/len(state["all_stars"]),2) | |
| if state["all_stars"] else 0) | |
| done = (f"### Well done, **{state['student_name']}**!\n\n" | |
| f"Completed **{state['round_num']}** rounds.\n\n" | |
| f"**Final Level:** {state['level']}\n\n" | |
| f"**Average Stars (saved):** {avg:.2f} / 8 {stars_display(round(avg))}") | |
| return ( | |
| state, {"shown_at": None, "hidden": [False]*MAX_QUESTIONS, "mode": "disappearing"}, | |
| gr.update(visible=False), gr.update(visible=True), | |
| done, "", | |
| passage_html(""), | |
| *q_updates([], False), *a_updates([], False), | |
| gr.update(visible=False), gr.update(visible=False), | |
| *ma_updates_hide(), | |
| gr.update(visible=False), *rw_updates([], False), | |
| gr.update(visible=False), "", "", | |
| gr.update(visible=False), | |
| ) | |
| total = len(state["indices"]) | |
| return ( | |
| state, {"shown_at": None, "hidden": [False]*MAX_QUESTIONS, "mode": "disappearing"}, | |
| gr.update(visible=True), gr.update(visible=False), | |
| "", | |
| f"### {state['student_name']} | Class {state['student_grade']} | " | |
| f"Level {state['level']} | Passage {state['ptr']} of {total}", | |
| passage_html(state["current_passage"]), | |
| *q_updates(state["current_questions"], True), | |
| *a_updates(state["current_questions"], True), | |
| gr.update(visible=False), gr.update(visible=True), | |
| *ma_updates_hide(), | |
| gr.update(visible=False), *rw_updates([], False), | |
| gr.update(visible=False), "", "", | |
| gr.update(visible=False), | |
| ) | |
| btn_next.click( | |
| cb_next, | |
| inputs=[sess], | |
| outputs=[ | |
| sess, ma_timer_state, | |
| quiz_panel, done_panel, done_md, | |
| status_md, passage_box, | |
| *q_labels, *a_boxes, | |
| thinking_md, btn_submit, | |
| *ma_cards, | |
| rewrite_hdr, *rw_boxes, | |
| btn_submit_rw, | |
| result_md, result2_md, | |
| btn_next, | |
| ], | |
| ) | |
| if __name__ == "__main__": | |
| demo.launch() |