File size: 18,849 Bytes
e2e538e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
fc1ed9c
f56945a
e2e538e
bc2af72
e2e538e
bc2af72
e2e538e
bc2af72
 
 
e2e538e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7602c79
e2e538e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc2af72
e2e538e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc2af72
e2e538e
 
 
 
bc2af72
e2e538e
 
bc2af72
e2e538e
 
 
bc2af72
e2e538e
bc2af72
e2e538e
 
bc2af72
 
e2e538e
 
 
 
 
 
 
 
 
 
 
 
 
bc2af72
e2e538e
 
 
 
 
bc2af72
e2e538e
bc2af72
 
e2e538e
 
 
 
 
 
 
 
 
 
 
 
bc2af72
e2e538e
 
 
 
bc2af72
 
e2e538e
 
 
 
bc2af72
e2e538e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc2af72
e2e538e
bc2af72
e2e538e
 
 
 
 
 
 
bc2af72
 
e2e538e
7602c79
e2e538e
7602c79
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2e538e
 
 
 
 
 
 
bc2af72
 
e2e538e
 
 
fc1ed9c
e2e538e
7602c79
 
e2e538e
7602c79
bc2af72
e2e538e
 
 
 
 
 
 
 
7602c79
e2e538e
 
bc2af72
 
e2e538e
 
 
 
 
bc2af72
 
e2e538e
 
 
 
7602c79
bc2af72
e2e538e
 
 
7602c79
bc2af72
e2e538e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7602c79
 
 
 
 
 
 
 
bc2af72
e2e538e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7602c79
 
bc2af72
 
e2e538e
 
 
 
912053a
e2e538e
 
 
 
 
 
 
 
912053a
bc2af72
e2e538e
7602c79
e2e538e
7602c79
 
912053a
e2e538e
 
bc2af72
 
e2e538e
7602c79
e2e538e
bc2af72
912053a
fc1ed9c
bc2af72
e2e538e
 
 
7602c79
e2e538e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a59c953
 
e2e538e
 
 
 
 
 
 
 
 
 
 
a59c953
e2e538e
 
 
 
7602c79
 
 
 
 
 
 
e2e538e
 
 
 
 
 
7602c79
 
 
 
 
 
e2e538e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bc2af72
e2e538e
 
 
 
 
 
 
 
bc2af72
 
 
e2e538e
 
 
 
 
 
 
 
 
 
 
 
 
912053a
bc2af72
e2e538e
 
 
bc2af72
e2e538e
 
 
 
 
 
 
bc2af72
912053a
 
bc2af72
e2e538e
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
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
"""
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"<details>\n<summary><b>Show AI Explanation</b></summary>\n\n{_format_latex(explanation)}\n\n</details>\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()