Rajarshi255's picture
Update app.py
a4921cc verified
Raw History Blame Contribute Delete
18.1 kB
"""
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()