""" 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 """ # ============================================================= # 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 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