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