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
3
+ -------------------
4
+ Kids pick a book + page range, Gemini generates MCQs from the rendered pages,
5
+ score is computed, stars awarded, row written to Google Sheet.
6
+
7
+ Architecture:
8
+ - Single HF Space, all classes/subjects in /books/<class>/<subject>.pdf
9
+ - PDF pages rendered on demand with PyMuPDF (no pre-splitting)
10
+ - Gemini 2.5 Flash-Lite for vision + MCQ generation (cheapest multimodal)
11
+ - gspread writes to the Star Bank ledger
12
+ """
13
+
14
+ import os
15
+ import io
16
+ import json
17
+ import re
18
+ import base64
19
+ import datetime
20
+ from pathlib import Path
21
+
22
+ import fitz # PyMuPDF
23
+ import gradio as gr
24
+ from PIL import Image
25
+ from google import genai
26
+ from google.genai import types
27
+ import gspread
28
+ from google.oauth2.service_account import Credentials
29
+
30
+ # ============================================================
31
+ # CONFIG
32
+ # ============================================================
33
+
34
+ BOOKS_DIR = Path("books") # e.g. books/class6/amader_prithibi.pdf
35
+ RENDER_DPI = 110 # balance: clarity vs token cost
36
+ MAX_PAGES_PER_QUIZ = 10 # safety cap
37
+ NUM_QUESTIONS = 5 # MCQs per quiz
38
+ STARS_FORMULA = lambda pct: max(0, int(pct // 20)) # 100% = 5 stars, 80% = 4, etc.
39
+
40
+ GEMINI_MODEL = "gemini-2.5-flash-lite"
41
+ SHEET_NAME = "MicroTest_star_App" # Google Sheet name
42
+ WORKSHEET_TITLE = "QuizLog"
43
+
44
+ # ============================================================
45
+ # SETUP
46
+ # ============================================================
47
+
48
+ # Gemini client (API key from HF Space secret)
49
+ client = genai.Client(api_key=os.environ["GEMINI_API_KEY"])
50
+
51
+ # Google Sheets client (service account JSON pasted into HF secret as one string)
52
+ def get_sheet():
53
+ creds_json = os.environ["GOOGLE_SERVICE_ACCOUNT_JSON"]
54
+ creds_dict = json.loads(creds_json)
55
+ scopes = [
56
+ "https://www.googleapis.com/auth/spreadsheets",
57
+ "https://www.googleapis.com/auth/drive",
58
+ ]
59
+ creds = Credentials.from_service_account_info(creds_dict, scopes=scopes)
60
+ gc = gspread.authorize(creds)
61
+ sh = gc.open(SHEET_NAME)
62
+ try:
63
+ ws = sh.worksheet(WORKSHEET_TITLE)
64
+ except gspread.WorksheetNotFound:
65
+ ws = sh.add_worksheet(title=WORKSHEET_TITLE, rows=2000, cols=12)
66
+ ws.append_row([
67
+ "Timestamp", "Name", "Class", "RollNo", "Language",
68
+ "Book", "PageFrom", "PageTo", "ScorePct", "StarsAwarded",
69
+ "Correct", "Total",
70
+ ])
71
+ return ws
72
+
73
+ # ============================================================
74
+ # BOOK DISCOVERY
75
+ # ============================================================
76
+
77
+ def list_classes():
78
+ """Return ['Class 5', 'Class 6', ...] based on folders in /books"""
79
+ if not BOOKS_DIR.exists():
80
+ return []
81
+ folders = sorted([p.name for p in BOOKS_DIR.iterdir() if p.is_dir()])
82
+ # Convert 'class6' -> 'Class 6' for display
83
+ return [f.replace("class", "Class ").strip() for f in folders]
84
+
85
+ def books_for_class(class_label):
86
+ """Given 'Class 6', return list of book titles."""
87
+ if not class_label:
88
+ return []
89
+ folder = BOOKS_DIR / class_label.replace("Class ", "class").strip()
90
+ if not folder.exists():
91
+ return []
92
+ return sorted([p.stem.replace("_", " ").title() for p in folder.glob("*.pdf")])
93
+
94
+ def pdf_path_for(class_label, book_title):
95
+ """Resolve 'Class 6' + 'Amader Prithibi' to actual file path."""
96
+ folder = BOOKS_DIR / class_label.replace("Class ", "class").strip()
97
+ filename = book_title.lower().replace(" ", "_") + ".pdf"
98
+ return folder / filename
99
+
100
+ def page_count(pdf_path):
101
+ if not pdf_path.exists():
102
+ return 0
103
+ with fitz.open(pdf_path) as doc:
104
+ return doc.page_count
105
+
106
+ # ============================================================
107
+ # PAGE RENDERING
108
+ # ============================================================
109
+
110
+ def render_pages(pdf_path, page_from, page_to):
111
+ """Render pages [page_from..page_to] (1-indexed, inclusive) as PIL images."""
112
+ images = []
113
+ with fitz.open(pdf_path) as doc:
114
+ n = doc.page_count
115
+ page_from = max(1, page_from)
116
+ page_to = min(n, page_to)
117
+ for i in range(page_from - 1, page_to):
118
+ page = doc.load_page(i)
119
+ zoom = RENDER_DPI / 72
120
+ mat = fitz.Matrix(zoom, zoom)
121
+ pix = page.get_pixmap(matrix=mat, alpha=False)
122
+ img = Image.open(io.BytesIO(pix.tobytes("jpeg", jpg_quality=80)))
123
+ images.append(img)
124
+ return images
125
+
126
+ # ============================================================
127
+ # MCQ GENERATION
128
+ # ============================================================
129
+
130
+ MCQ_PROMPT_TEMPLATE = """You are a careful exam-setter for school children in West Bengal, India.
131
+
132
+ You will be shown {n_pages} page image(s) from a {class_label} textbook titled "{book_title}".
133
+
134
+ Your task: generate exactly {num_q} multiple-choice questions in {language}.
135
+
136
+ STRICT RULES:
137
+ 1. Each question must be answerable from the page content. Do not invent facts.
138
+ 2. Each question has exactly 4 options labeled A, B, C, D. Only ONE option is correct.
139
+ 3. The wrong options ("distractors") must be plausible but clearly wrong on careful reading.
140
+ 4. Questions should test understanding, not trivia (avoid "what was the page number" type questions).
141
+ 5. Mix difficulty: 2 easy (direct recall), 2 medium (one inference step), 1 harder (connecting two facts).
142
+ 6. Language: {language}. If Bengali, use simple Class 6 vocabulary. Avoid technical jargon.
143
+ 7. If the pages contain a diagram, map, or image, you MAY ask about it.
144
+ 8. If a page is mostly blank, decorative, or the table of contents, skip it and use other pages.
145
+
146
+ OUTPUT FORMAT β€” return ONLY a JSON array, no prose, no markdown fences:
147
+ [
148
+ {{
149
+ "question": "...",
150
+ "options": {{"A": "...", "B": "...", "C": "...", "D": "..."}},
151
+ "correct": "B",
152
+ "explanation": "One short sentence explaining why."
153
+ }},
154
+ ...
155
+ ]
156
+ """
157
+
158
+ def generate_mcqs(images, class_label, book_title, language, num_q=NUM_QUESTIONS):
159
+ """Send rendered pages to Gemini, return parsed MCQ list."""
160
+ prompt = MCQ_PROMPT_TEMPLATE.format(
161
+ n_pages=len(images),
162
+ class_label=class_label,
163
+ book_title=book_title,
164
+ language=language,
165
+ num_q=num_q,
166
+ )
167
+
168
+ # Build content: prompt + each image
169
+ parts = [prompt]
170
+ for img in images:
171
+ buf = io.BytesIO()
172
+ img.save(buf, format="JPEG", quality=80)
173
+ parts.append(types.Part.from_bytes(
174
+ data=buf.getvalue(),
175
+ mime_type="image/jpeg",
176
+ ))
177
+
178
+ response = client.models.generate_content(
179
+ model=GEMINI_MODEL,
180
+ contents=parts,
181
+ )
182
+
183
+ text = response.text.strip()
184
+ # Strip markdown fences if model added them despite instructions
185
+ text = re.sub(r"^```(?:json)?\s*", "", text)
186
+ text = re.sub(r"\s*```$", "", text)
187
+
188
+ try:
189
+ mcqs = json.loads(text)
190
+ except json.JSONDecodeError as e:
191
+ raise RuntimeError(f"Gemini returned non-JSON: {text[:300]}") from e
192
+
193
+ # Validate shape
194
+ cleaned = []
195
+ for q in mcqs:
196
+ if not all(k in q for k in ("question", "options", "correct")):
197
+ continue
198
+ if not all(k in q["options"] for k in ("A", "B", "C", "D")):
199
+ continue
200
+ if q["correct"] not in ("A", "B", "C", "D"):
201
+ continue
202
+ cleaned.append(q)
203
+ return cleaned
204
+
205
+ # ============================================================
206
+ # SCORING
207
+ # ============================================================
208
+
209
+ def score_quiz(mcqs, answers):
210
+ """answers is list of 'A'/'B'/'C'/'D'/None aligned with mcqs."""
211
+ correct = 0
212
+ feedback = []
213
+ for q, a in zip(mcqs, answers):
214
+ is_right = (a == q["correct"])
215
+ if is_right:
216
+ correct += 1
217
+ feedback.append({
218
+ "question": q["question"],
219
+ "your_answer": a or "(no answer)",
220
+ "correct_answer": q["correct"],
221
+ "correct_text": q["options"][q["correct"]],
222
+ "is_right": is_right,
223
+ "explanation": q.get("explanation", ""),
224
+ })
225
+ total = len(mcqs)
226
+ pct = round(100 * correct / total, 1) if total else 0
227
+ stars = STARS_FORMULA(pct)
228
+ return correct, total, pct, stars, feedback
229
+
230
+ def log_to_sheet(name, class_label, roll, language, book, p_from, p_to, pct, stars, correct, total):
231
+ try:
232
+ ws = get_sheet()
233
+ ws.append_row([
234
+ datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
235
+ name, class_label, roll, language,
236
+ book, p_from, p_to, pct, stars, correct, total,
237
+ ])
238
+ return True
239
+ except Exception as e:
240
+ print(f"[Sheet write failed] {e}")
241
+ return False
242
+
243
+ # ============================================================
244
+ # GRADIO UI
245
+ # ============================================================
246
+
247
+ with gr.Blocks(title="Singerkone Quiz", theme=gr.themes.Soft()) as demo:
248
+ state_mcqs = gr.State([])
249
+ state_meta = gr.State({})
250
+
251
+ gr.Markdown("# πŸ“š Singerkone Quiz\n*Pick a book, pick pages, answer the quiz, earn stars.*")
252
+
253
+ # ----- Login screen -----
254
+ with gr.Group(visible=True) as login_view:
255
+ gr.Markdown("### Step 1 β€” Tell us about you")
256
+ with gr.Row():
257
+ name_in = gr.Textbox(label="Your name", placeholder="e.g. Srijan")
258
+ roll_in = gr.Textbox(label="Roll number", placeholder="optional")
259
+ with gr.Row():
260
+ class_in = gr.Dropdown(choices=list_classes(), label="Your class")
261
+ lang_in = gr.Radio(["English", "Bengali"], value="English", label="Quiz language")
262
+
263
+ gr.Markdown("### Step 2 β€” Pick book & pages")
264
+ book_in = gr.Dropdown(choices=[], label="Book")
265
+ page_info = gr.Markdown("")
266
+ with gr.Row():
267
+ page_from_in = gr.Number(label="From page", value=1, precision=0, minimum=1)
268
+ page_to_in = gr.Number(label="To page", value=3, precision=0, minimum=1)
269
+
270
+ start_btn = gr.Button("🎯 Generate Quiz", variant="primary")
271
+ start_status = gr.Markdown("")
272
+
273
+ # ----- Quiz screen -----
274
+ with gr.Group(visible=False) as quiz_view:
275
+ gr.Markdown("### πŸ“ Answer all questions")
276
+ q_displays = []
277
+ q_radios = []
278
+ for i in range(NUM_QUESTIONS):
279
+ md = gr.Markdown(f"**Q{i+1}.**")
280
+ rb = gr.Radio(choices=["A", "B", "C", "D"], label="Your answer")
281
+ q_displays.append(md)
282
+ q_radios.append(rb)
283
+ submit_btn = gr.Button("βœ… Submit Answers", variant="primary")
284
+
285
+ # ----- Result screen -----
286
+ with gr.Group(visible=False) as result_view:
287
+ result_summary = gr.Markdown("")
288
+ result_detail = gr.Markdown("")
289
+ again_btn = gr.Button("πŸ” Take another quiz")
290
+
291
+ # ============================================================
292
+ # CALLBACKS
293
+ # ============================================================
294
+
295
+ def update_books(class_label):
296
+ choices = books_for_class(class_label)
297
+ return gr.update(choices=choices, value=choices[0] if choices else None)
298
+
299
+ def update_page_info(class_label, book_title):
300
+ if not class_label or not book_title:
301
+ return ""
302
+ p = pdf_path_for(class_label, book_title)
303
+ n = page_count(p)
304
+ if n == 0:
305
+ return "⚠️ Book file not found."
306
+ return f"πŸ“– This book has **{n} pages**. Pick a range up to {MAX_PAGES_PER_QUIZ} pages."
307
+
308
+ class_in.change(update_books, inputs=class_in, outputs=book_in)
309
+ book_in.change(update_page_info, inputs=[class_in, book_in], outputs=page_info)
310
+
311
+ def start_quiz(name, roll, class_label, lang, book, p_from, p_to):
312
+ # Validation
313
+ if not name or not class_label or not book:
314
+ return (
315
+ gr.update(), # login_view
316
+ gr.update(), # quiz_view
317
+ gr.update(), # result_view
318
+ "⚠️ Please fill name, class, and book.",
319
+ [], {},
320
+ *[gr.update() for _ in range(NUM_QUESTIONS * 2)],
321
+ )
322
+ p_from, p_to = int(p_from), int(p_to)
323
+ if p_to < p_from:
324
+ p_from, p_to = p_to, p_from
325
+ if p_to - p_from + 1 > MAX_PAGES_PER_QUIZ:
326
+ return (
327
+ gr.update(), gr.update(), gr.update(),
328
+ f"⚠️ Pick at most {MAX_PAGES_PER_QUIZ} pages at a time.",
329
+ [], {},
330
+ *[gr.update() for _ in range(NUM_QUESTIONS * 2)],
331
+ )
332
+
333
+ pdf_path = pdf_path_for(class_label, book)
334
+ if not pdf_path.exists():
335
+ return (
336
+ gr.update(), gr.update(), gr.update(),
337
+ f"⚠️ Book file missing: {pdf_path}",
338
+ [], {},
339
+ *[gr.update() for _ in range(NUM_QUESTIONS * 2)],
340
+ )
341
+
342
+ try:
343
+ images = render_pages(pdf_path, p_from, p_to)
344
+ mcqs = generate_mcqs(images, class_label, book, lang)
345
+ if len(mcqs) < NUM_QUESTIONS:
346
+ # Pad warning but proceed with what we got
347
+ pass
348
+ mcqs = mcqs[:NUM_QUESTIONS]
349
+ except Exception as e:
350
+ return (
351
+ gr.update(), gr.update(), gr.update(),
352
+ f"⚠️ Quiz generation failed: {e}",
353
+ [], {},
354
+ *[gr.update() for _ in range(NUM_QUESTIONS * 2)],
355
+ )
356
+
357
+ # Build question displays
358
+ q_updates = []
359
+ for i in range(NUM_QUESTIONS):
360
+ if i < len(mcqs):
361
+ q = mcqs[i]
362
+ txt = (
363
+ f"**Q{i+1}. {q['question']}**\n\n"
364
+ f"- **A.** {q['options']['A']}\n"
365
+ f"- **B.** {q['options']['B']}\n"
366
+ f"- **C.** {q['options']['C']}\n"
367
+ f"- **D.** {q['options']['D']}"
368
+ )
369
+ q_updates.append(gr.update(value=txt, visible=True))
370
+ q_updates.append(gr.update(value=None, visible=True))
371
+ else:
372
+ q_updates.append(gr.update(visible=False))
373
+ q_updates.append(gr.update(visible=False))
374
+
375
+ meta = {
376
+ "name": name, "roll": roll or "",
377
+ "class": class_label, "lang": lang,
378
+ "book": book, "from": p_from, "to": p_to,
379
+ }
380
+ return (
381
+ gr.update(visible=False), # hide login
382
+ gr.update(visible=True), # show quiz
383
+ gr.update(visible=False), # hide result
384
+ "",
385
+ mcqs, meta,
386
+ *q_updates,
387
+ )
388
+
389
+ start_btn.click(
390
+ start_quiz,
391
+ inputs=[name_in, roll_in, class_in, lang_in, book_in, page_from_in, page_to_in],
392
+ outputs=[login_view, quiz_view, result_view, start_status, state_mcqs, state_meta] +
393
+ [item for pair in zip(q_displays, q_radios) for item in pair],
394
+ )
395
+
396
+ def submit_quiz(mcqs, meta, *answers):
397
+ correct, total, pct, stars, feedback = score_quiz(mcqs, list(answers))
398
+ logged = log_to_sheet(
399
+ meta["name"], meta["class"], meta["roll"], meta["lang"],
400
+ meta["book"], meta["from"], meta["to"],
401
+ pct, stars, correct, total,
402
+ )
403
+
404
+ summary = (
405
+ f"## πŸŽ‰ Result for {meta['name']}\n\n"
406
+ f"**Score:** {correct} / {total} ({pct}%)\n\n"
407
+ f"**Stars earned:** {'⭐' * stars if stars else 'β€” (try again!)'}\n\n"
408
+ f"{'βœ… Saved to Star Bank.' if logged else '⚠️ Could not save to Star Bank β€” tell sir.'}"
409
+ )
410
+
411
+ detail_lines = ["---", "### Review", ""]
412
+ for i, f in enumerate(feedback):
413
+ icon = "βœ…" if f["is_right"] else "❌"
414
+ detail_lines.append(
415
+ f"**{icon} Q{i+1}.** {f['question']}\n\n"
416
+ f"Your answer: **{f['your_answer']}** | "
417
+ f"Correct: **{f['correct_answer']}. {f['correct_text']}**\n\n"
418
+ f"*{f['explanation']}*\n"
419
+ )
420
+ detail = "\n".join(detail_lines)
421
+
422
+ return (
423
+ gr.update(visible=False),
424
+ gr.update(visible=False),
425
+ gr.update(visible=True),
426
+ summary,
427
+ detail,
428
+ )
429
+
430
+ submit_btn.click(
431
+ submit_quiz,
432
+ inputs=[state_mcqs, state_meta] + q_radios,
433
+ outputs=[login_view, quiz_view, result_view, result_summary, result_detail],
434
+ )
435
+
436
+ def reset():
437
+ return (
438
+ gr.update(visible=True),
439
+ gr.update(visible=False),
440
+ gr.update(visible=False),
441
+ "", "",
442
+ )
443
+
444
+ again_btn.click(
445
+ reset,
446
+ outputs=[login_view, quiz_view, result_view, result_summary, result_detail],
447
+ )
448
+
449
+ if __name__ == "__main__":
450
+ demo.launch()