""" MCQ Quiz Solver ================ Upload photo(s) of multiple-choice questions -> GOT-OCR-2.0 reads the text -> Qwen2.5-1.5B-Instruct solves each question -> you get quizzed one question at a time against the AI's answers -> a final score report. Deploy on Hugging Face Spaces (Gradio SDK). For best performance, select "ZeroGPU" hardware in the Space settings -- the @spaces.GPU decorator below will then transparently borrow an A100 for each OCR / LLM call. The app also runs (slowly) on CPU-only or a normal GPU Space with no code changes needed. """ import re import traceback from typing import Dict, List, Optional, Tuple import gradio as gr import torch from pydantic import BaseModel, Field from transformers import ( AutoModelForCausalLM, AutoModelForImageTextToText, AutoProcessor, AutoTokenizer, ) # --------------------------------------------------------------------------- # ZeroGPU support # --------------------------------------------------------------------------- try: import spaces HAS_SPACES = True except ImportError: HAS_SPACES = False class _DummySpaces: @staticmethod def GPU(fn=None, **kwargs): if fn is None: def _wrap(f): return f return _wrap return fn spaces = _DummySpaces() # --------------------------------------------------------------------------- # Config # --------------------------------------------------------------------------- DEVICE = "cuda" if torch.cuda.is_available() else "cpu" DTYPE = torch.bfloat16 if DEVICE == "cuda" else torch.float32 OCR_MODEL_ID = "stepfun-ai/GOT-OCR-2.0-hf" LLM_MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct" LETTERS = ["A", "B", "C", "D", "E", "F"] # --------------------------------------------------------------------------- # Model loading (once, at process start) # --------------------------------------------------------------------------- print(f"[startup] device = {DEVICE}") print(f"[startup] loading OCR model: {OCR_MODEL_ID} ...") ocr_processor = AutoProcessor.from_pretrained(OCR_MODEL_ID, use_fast=True) ocr_model = AutoModelForImageTextToText.from_pretrained( OCR_MODEL_ID, torch_dtype=DTYPE, ).to(DEVICE) ocr_model.eval() print(f"[startup] loading LLM: {LLM_MODEL_ID} ...") llm_tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_ID) llm_model = AutoModelForCausalLM.from_pretrained( LLM_MODEL_ID, torch_dtype=DTYPE, ).to(DEVICE) llm_model.eval() OUTLINES_AVAILABLE = False outlines_model = None try: import outlines outlines_model = outlines.from_transformers(llm_model, llm_tokenizer) OUTLINES_AVAILABLE = True print("[startup] Outlines structured generation enabled.") except Exception as exc: # noqa: BLE001 print(f"[startup] Outlines unavailable, will use fallback generation. ({exc})") class AnswerFormat(BaseModel): correct_option: str = Field(description="The letter of the correct option, e.g. 'A'") explanation: str = Field(description="A very short, step-by-step explanation") # --------------------------------------------------------------------------- # OCR # --------------------------------------------------------------------------- @spaces.GPU(duration=90) def run_ocr(image_path: str) -> str: """Run GOT-OCR-2.0 on a single image and return formatted (markdown/LaTeX) text.""" inputs = ocr_processor( image_path, return_tensors="pt", format=True, crop_to_patches=True, max_patches=4, ).to(DEVICE) with torch.no_grad(): generate_ids = ocr_model.generate( **inputs, do_sample=False, tokenizer=ocr_processor.tokenizer, stop_strings="<|im_end|>", max_new_tokens=4096, ) output_text = ocr_processor.decode( generate_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True, ) return output_text # --------------------------------------------------------------------------- # Parsing OCR text into MCQ questions # --------------------------------------------------------------------------- _OPTION_RE = re.compile(r"^\(?([a-fA-F])[\)\.\:]\s*(.*)") _QNUM_RE = re.compile(r"^\(?\d+[\)\.\:]\s*(.*)") def parse_questions(ocr_text: str) -> List[Dict]: """Turn raw OCR text into a list of {"question_text", "options": [...]} dicts.""" questions: List[Dict] = [] q_chunks: List[str] = [] options: List[str] = [] def flush() -> None: nonlocal q_chunks, options if q_chunks and options: questions.append( { "question_text": " ".join(q_chunks).strip(), "options": list(options), } ) q_chunks = [] options = [] for raw_line in ocr_text.splitlines(): line = raw_line.strip() if not line: continue opt_match = _OPTION_RE.match(line) if opt_match: options.append(opt_match.group(2).strip()) continue if options: flush() q_match = _QNUM_RE.match(line) if q_match: line = q_match.group(1).strip() q_chunks.append(line) flush() return questions # --------------------------------------------------------------------------- # LLM answer generation # --------------------------------------------------------------------------- def _build_prompt(question_text: str, options: List[str]) -> str: lines = [f"Question: {question_text}"] for i, opt in enumerate(options): label = LETTERS[i] if i < len(LETTERS) else str(i) lines.append(f"{label}) {opt}") lines.append( "\nAnalyze the question and respond with the correct option letter " "and a very short explanation." ) raw_content = "\n".join(lines) if getattr(llm_tokenizer, "chat_template", None): return llm_tokenizer.apply_chat_template( [{"role": "user", "content": raw_content}], tokenize=False, add_generation_prompt=True, ) return raw_content def _fallback_answer(prompt: str) -> Tuple[str, str]: """Plain generation + regex extraction, used if Outlines isn't usable.""" inputs = llm_tokenizer(prompt, return_tensors="pt").to(DEVICE) with torch.no_grad(): output_ids = llm_model.generate( **inputs, max_new_tokens=400, do_sample=False, ) text = llm_tokenizer.decode( output_ids[0, inputs["input_ids"].shape[1]:], skip_special_tokens=True, ) match = re.search(r"\b([A-F])\b", text.upper()) letter = match.group(1) if match else "A" explanation = text.strip()[:400] or "No explanation generated." return letter, explanation @spaces.GPU(duration=45) def generate_ai_answer(question_text: str, options: List[str]) -> Tuple[str, str]: """Return (correct_option_letter, explanation) for one MCQ.""" prompt = _build_prompt(question_text, options) if OUTLINES_AVAILABLE: try: result = outlines_model(prompt, AnswerFormat, max_new_tokens=400) if isinstance(result, AnswerFormat): parsed = result elif isinstance(result, str): parsed = AnswerFormat.model_validate_json(result) else: parsed = AnswerFormat.model_validate(result) letter = re.sub(r"[^A-Fa-f]", "", parsed.correct_option).upper()[:1] or "A" return letter, parsed.explanation except Exception as exc: # noqa: BLE001 print(f"[warn] Outlines generation failed, falling back: {exc}") return _fallback_answer(prompt) def process_single_image( image_path: str, progress: Optional[gr.Progress], img_idx: int, total_imgs: int, ) -> List[Dict]: ocr_text = run_ocr(image_path) questions = parse_questions(ocr_text) for qi, q in enumerate(questions): if progress is not None: frac = (img_idx + (qi / max(len(questions), 1))) / max(total_imgs, 1) progress( frac, desc=f"Image {img_idx + 1}/{total_imgs}: solving question {qi + 1}/{len(questions)}", ) letter, explanation = generate_ai_answer(q["question_text"], q["options"]) q["ai_answer"] = letter q["ai_explanation"] = explanation return questions def run_pipeline(image_paths: List[str], progress: gr.Progress) -> List[Dict]: if not image_paths: raise gr.Error("Please upload at least one image before processing.") all_questions: List[Dict] = [] total = len(image_paths) for i, path in enumerate(image_paths): progress(i / total, desc=f"Reading image {i + 1} of {total}...") try: qs = process_single_image(path, progress, i, total) except Exception as exc: # noqa: BLE001 traceback.print_exc() raise gr.Error(f"Failed to process image {i + 1}: {exc}") from exc all_questions.extend(qs) progress(1.0, desc="Done!") if not all_questions: raise gr.Error( "No multiple-choice questions were detected. Please make sure the " "image(s) show clearly readable text with lettered options like " "a), b), c)..." ) return all_questions # --------------------------------------------------------------------------- # Formatting & Gradio callbacks # --------------------------------------------------------------------------- def _format_latex(text: str) -> str: """Helper to convert standard OCR math blocks into Gradio-supported LaTeX delimiters.""" if not text: return "" text = str(text) # Replace \( and \) with $ ... Replace \[ and \] with $$ text = text.replace(r"\(", "$").replace(r"\)", "$") text = text.replace(r"\[", "$$").replace(r"\]", "$$") return text def _get_q_md(q: Dict) -> str: """Formats question and options directly into Markdown to ensure LaTeX renders.""" lines = [f"**{_format_latex(q['question_text'])}**\n"] for i, opt in enumerate(q["options"]): lines.append(f"* **{LETTERS[i]})** {_format_latex(opt)}") return "\n".join(lines) def _extract_paths(files) -> List[str]: if not files: return [] paths = [] for f in files: paths.append(f if isinstance(f, str) else getattr(f, "name", None)) return [p for p in paths if p] def start_quiz(files, progress=gr.Progress()): image_paths = _extract_paths(files) questions = run_pipeline(image_paths, progress) first_q = questions[0] # Provide just the letters for the radio options. The actual text + LaTeX is in the markdown. choices = [LETTERS[i] for i in range(len(first_q["options"]))] progress_text = f"**Question 1 of {len(questions)}**" q_md_text = _get_q_md(first_q) return ( questions, # questions_state 0, # idx_state [], # answers_state gr.update(visible=False), # upload_group gr.update(visible=True), # quiz_group gr.update(visible=False), # report_group progress_text, # progress_md q_md_text, # question_md gr.update(choices=choices, value=None), # options_radio ) def _normalize_letter(value) -> Optional[str]: if not value: return None match = re.search(r"[A-Fa-f]", str(value)) return match.group(0).upper() if match else None def build_report(questions: List[Dict], answers: List[Optional[str]]) -> str: total = len(questions) correct = wrong = skipped = 0 rows = [] explanations_md = ["\n\n### Detailed Explanations\n"] for i, q in enumerate(questions): user_ans = answers[i] if i < len(answers) else None ai_letter = _normalize_letter(q.get("ai_answer")) explanation = q.get("ai_explanation", "No explanation provided.") if user_ans is None: skipped += 1 result = "⏭️ Skipped" user_letter = None else: user_letter = _normalize_letter(user_ans) if ai_letter and user_letter == ai_letter: correct += 1 result = "✅ Correct" else: wrong += 1 result = "❌ Wrong" rows.append( f"| {i + 1} | {result} | {user_letter or '-'} | {ai_letter or '-'} |" ) # Build explanation section allowing user to click for details explanations_md.append(f"#### Question {i + 1}") explanations_md.append(f"{_format_latex(q['question_text'])}\n") for j, opt in enumerate(q["options"]): explanations_md.append(f"* **{LETTERS[j]})** {_format_latex(opt)}") explanations_md.append(f"\n**Your Answer:** {user_letter or '-'} | **Correct Answer:** {ai_letter or '-'}\n") explanations_md.append(f"
\nShow AI Explanation\n\n{_format_latex(explanation)}\n\n
\n\n---\n") score_pct = (correct / total * 100) if total else 0.0 header = ( "## 🎉 Quiz Complete!\n\n" "| Metric | Value |\n" "|---|---|\n" f"| Total Questions | {total} |\n" f"| ✅ Correctly Solved | {correct} |\n" f"| ❌ Wrong | {wrong} |\n" f"| ⏭️ Skipped | {skipped} |\n" f"| **Final Score** | **{score_pct:.1f}%** |\n\n" "### Question-by-question breakdown\n\n" "| # | Result | Your answer | AI answer |\n" "|---|---|---|---|\n" ) return header + "\n".join(rows) + "\n".join(explanations_md) def _advance(questions: List[Dict], idx: int, answers: List[Optional[str]]): new_idx = idx + 1 if new_idx >= len(questions): report = build_report(questions, answers) return ( new_idx, # idx_state answers, # answers_state gr.update(visible=False), # quiz_group gr.update(visible=True), # report_group gr.update(), # progress_md (unchanged) gr.update(), # question_md (unchanged) gr.update(), # options_radio (unchanged) report, # report_md ) q = questions[new_idx] choices = [LETTERS[i] for i in range(len(q["options"]))] progress_text = f"**Question {new_idx + 1} of {len(questions)}**" q_md_text = _get_q_md(q) return ( new_idx, answers, gr.update(visible=True), gr.update(visible=False), progress_text, q_md_text, gr.update(choices=choices, value=None), gr.update(), ) def submit_answer(selected, questions, idx, answers): if not selected: raise gr.Error("Please select an option, or click 'Skip Question' if you're unsure.") letter = selected.strip().upper() return _advance(questions, idx, answers + [letter]) def skip_question(questions, idx, answers): return _advance(questions, idx, answers + [None]) def restart_quiz(): return ( [], # questions_state 0, # idx_state [], # answers_state gr.update(visible=True), # upload_group gr.update(visible=False), # quiz_group gr.update(visible=False), # report_group None, # image_input ) # --------------------------------------------------------------------------- # UI # --------------------------------------------------------------------------- with gr.Blocks(title="MCQ Quiz Solver", theme=gr.themes.Soft()) as demo: questions_state = gr.State([]) idx_state = gr.State(0) answers_state = gr.State([]) gr.Markdown( "# Mockify: MCQ practicing battle-ground\n\n" "Upload photo(s) of multiple-choice questions Ex: IOE exam etc. An OCR model reads them, " "an AI model solves them, and then you get quizzed against the AI's answers." ) with gr.Group(visible=True) as upload_group: image_input = gr.File( label="Upload one or more question images", file_count="multiple", file_types=["image"], ) process_btn = gr.Button("Process Images & Start Quiz", variant="primary") gr.Markdown( "\nIt may take a while after pressing the button. Please wait patiently." ) with gr.Group(visible=False) as quiz_group: progress_md = gr.Markdown() # Explicit latex configurations as backup safety question_md = gr.Markdown(latex_delimiters=[ {"left": "$$", "right": "$$", "display": True}, {"left": "$", "right": "$", "display": False}, {"left": "\\(", "right": "\\)", "display": False}, {"left": "\\[", "right": "\\]", "display": True} ]) options_radio = gr.Radio(label="Choose your answer", choices=[]) with gr.Row(): skip_btn = gr.Button("⏭️ Skip Question") next_btn = gr.Button("Submit & Next ➡️", variant="primary") with gr.Group(visible=False) as report_group: report_md = gr.Markdown(latex_delimiters=[ {"left": "$$", "right": "$$", "display": True}, {"left": "$", "right": "$", "display": False}, {"left": "\\(", "right": "\\)", "display": False}, {"left": "\\[", "right": "\\]", "display": True} ]) restart_btn = gr.Button("🔁 Start New Quiz", variant="primary") process_btn.click( fn=start_quiz, inputs=[image_input], outputs=[ questions_state, idx_state, answers_state, upload_group, quiz_group, report_group, progress_md, question_md, options_radio, ], ) next_btn.click( fn=submit_answer, inputs=[options_radio, questions_state, idx_state, answers_state], outputs=[ idx_state, answers_state, quiz_group, report_group, progress_md, question_md, options_radio, report_md, ], ) skip_btn.click( fn=skip_question, inputs=[questions_state, idx_state, answers_state], outputs=[ idx_state, answers_state, quiz_group, report_group, progress_md, question_md, options_radio, report_md, ], ) restart_btn.click( fn=restart_quiz, inputs=[], outputs=[ questions_state, idx_state, answers_state, upload_group, quiz_group, report_group, image_input, ], ) if __name__ == "__main__": demo.queue().launch()