pawanmakes commited on
Commit
e2e538e
·
1 Parent(s): b0f2192

Changed code to add a question grading system.

Browse files
Files changed (3) hide show
  1. README.md +3 -3
  2. app.py +482 -336
  3. requirements.txt +8 -4
README.md CHANGED
@@ -1,8 +1,8 @@
1
  ---
2
  title: Mockify
3
- emoji: 💻
4
- colorFrom: green
5
- colorTo: red
6
  sdk: gradio
7
  sdk_version: 6.21.0
8
  python_version: '3.12'
 
1
  ---
2
  title: Mockify
3
+ emoji: 📝
4
+ colorFrom: indigo
5
+ colorTo: pink
6
  sdk: gradio
7
  sdk_version: 6.21.0
8
  python_version: '3.12'
app.py CHANGED
@@ -1,397 +1,543 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
- import spaces
3
  import torch
4
- import re
5
- import json
6
- from PIL import Image
7
  from transformers import (
8
- AutoProcessor,
9
  AutoModelForImageTextToText,
 
10
  AutoTokenizer,
11
- AutoModelForCausalLM,
12
- )
13
- from typing import List
14
- from pydantic import BaseModel, Field
15
-
16
- # =============================================================================
17
- # Pipeline overview:
18
- # 1. GOT-OCR-2.0 -> reads the raw question/option text out of the image
19
- # 2. Qwen2.5-1.5B-Instruct -> solves each question ONE BY ONE, producing a
20
- # correct answer + a short explanation
21
- # 3. Gradio quiz UI -> lets the user answer, request a hint (the
22
- # explanation from step 2), and finally review
23
- # every answer against what the model decided
24
- # =============================================================================
25
-
26
- # --- 1. Global Model Initialization ---
27
- # For ZeroGPU spaces, load into CPU/RAM first.
28
- # Each model is moved onto the GPU inside its own @spaces.GPU-decorated
29
- # function, right before it's actually used.
30
-
31
- # 1a. OCR model - reads the MCQs out of the uploaded image
32
- model_id = "stepfun-ai/GOT-OCR-2.0-hf"
33
- model = AutoModelForImageTextToText.from_pretrained(model_id)
34
- processor = AutoProcessor.from_pretrained(model_id)
35
-
36
- # 1b. Solver model - works out the correct answer + explanation for every
37
- # question the OCR model extracted.
38
- solver_model_id = "Qwen/Qwen2.5-1.5B-Instruct"
39
- solver_tokenizer = AutoTokenizer.from_pretrained(solver_model_id)
40
- solver_model = AutoModelForCausalLM.from_pretrained(
41
- solver_model_id,
42
- torch_dtype=torch.bfloat16,
43
  )
44
 
45
- SOLVER_SYSTEM_PROMPT = (
46
- "You are an expert exam solver. You will be given a multiple-choice "
47
- "question and its options. Work out which option is correct, then "
48
- "respond with ONLY a single JSON object and nothing else - no markdown "
49
- "fences, no preamble, no extra commentary.\n\n"
50
- "The JSON object must have exactly this shape:\n"
51
- '{"answer": "<the correct option, copied verbatim from the options list>", '
52
- '"explanation": "<a concise 2-3 sentence explanation of why it is correct>"}'
53
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
55
 
56
- # --- 2. Pydantic Schemas ---
57
- class MCQOption(BaseModel):
58
- text: str = Field(description="The clean text content of the option, excluding any labels")
 
59
 
60
- class MCQQuestion(BaseModel):
61
- question_text: str = Field(description="The main question stem, completely clean of options")
62
- options: List[MCQOption]
 
63
 
 
 
 
64
 
65
- # --- 3. Post Processing Pipeline (OCR text -> raw MCQs) ---
66
- def post_process(ocr_text: str) -> list:
67
- """
68
- Parses raw OCR math text and returns a list of dictionaries
69
- formatted exactly for the Gradio state tracker.
70
- """
71
- lines = ocr_text.splitlines()
72
- questions_list = []
73
 
74
- current_question_chunks = []
75
- current_options = []
76
 
77
- option_pattern = re.compile(r'^[a-eA-E]\)\s*(.*)')
78
- question_num_pattern = re.compile(r'^\d+[\)\.]\s*(.*)')
79
 
80
- for line in lines:
81
- cleaned_line = line.strip()
82
- if not cleaned_line:
83
- continue
 
 
 
 
 
 
 
 
 
84
 
85
- opt_match = option_pattern.match(cleaned_line)
86
- if opt_match:
87
- option_payload = opt_match.group(1).strip()
88
- current_options.append(MCQOption(text=option_payload))
89
- else:
90
- if current_options:
91
- full_q_text = " ".join(current_question_chunks).strip()
92
- questions_list.append(
93
- MCQQuestion(question_text=full_q_text, options=current_options)
94
- )
95
- current_question_chunks = []
96
- current_options = []
97
-
98
- q_match = question_num_pattern.match(cleaned_line)
99
- if q_match:
100
- cleaned_line = q_match.group(1).strip()
101
-
102
- current_question_chunks.append(cleaned_line)
103
-
104
- if current_question_chunks and current_options:
105
- full_q_text = " ".join(current_question_chunks).strip()
106
- questions_list.append(
107
- MCQQuestion(question_text=full_q_text, options=current_options)
108
  )
 
109
 
110
- # Convert Pydantic models to the dictionary format Gradio expects
111
- formatted_mcqs = []
112
- for q in questions_list:
113
- options_texts = [opt.text for opt in q.options]
114
- formatted_mcqs.append({
115
- "q": q.question_text,
116
- "options": options_texts,
117
- # Placeholder until the solver model (Qwen) fills in the real answer.
118
- "a": options_texts[0] if options_texts else "",
119
- "explanation": "",
120
- })
121
-
122
- return formatted_mcqs
123
-
124
-
125
- # --- 4. Solver Pipeline Helpers (Qwen2.5-1.5B-Instruct) ---
126
- def match_option(candidate: str, options: List[str]):
127
- """
128
- Map the solver model's free-text answer back to one of the real option
129
- strings - handles the model echoing a label like 'a) ', or rewording an
130
- option very slightly.
131
- """
132
- candidate_clean = re.sub(r'^[a-eA-E][\)\.]\s*', '', candidate.strip().lower())
133
-
134
- for opt in options:
135
- if opt.strip().lower() == candidate_clean:
136
- return opt
137
-
138
- for opt in options:
139
- opt_clean = opt.strip().lower()
140
- if opt_clean and (opt_clean in candidate_clean or candidate_clean in opt_clean):
141
- return opt
142
-
143
- return None
144
-
145
-
146
- def parse_solver_response(response_text: str, options: List[str]):
147
- """
148
- Robustly extract {"answer": ..., "explanation": ...} from the model's
149
- raw text, falling back gracefully if it doesn't return clean JSON.
150
- """
151
- answer = options[0] if options else ""
152
- explanation = "The model did not return a usable explanation."
153
-
154
- json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
155
- if json_match:
156
- try:
157
- parsed = json.loads(json_match.group(0))
158
- raw_answer = str(parsed.get("answer", "")).strip()
159
- explanation = str(parsed.get("explanation", explanation)).strip()
160
-
161
- matched_option = match_option(raw_answer, options)
162
- if matched_option:
163
- answer = matched_option
164
- except (json.JSONDecodeError, AttributeError, TypeError):
165
- pass
166
-
167
- return answer, explanation
168
-
169
-
170
- def ask_solver_model(question: str, options: List[str], device: str):
171
- """Send a single question to Qwen and return (correct_answer, explanation)."""
172
- options_block = "\n".join(f"{chr(97 + i)}) {opt}" for i, opt in enumerate(options))
173
- user_prompt = f"Question: {question}\n\nOptions:\n{options_block}"
174
-
175
- messages = [
176
- {"role": "system", "content": SOLVER_SYSTEM_PROMPT},
177
- {"role": "user", "content": user_prompt},
178
- ]
179
- prompt_text = solver_tokenizer.apply_chat_template(
180
- messages, tokenize=False, add_generation_prompt=True
181
- )
182
- model_inputs = solver_tokenizer([prompt_text], return_tensors="pt").to(device)
183
 
184
- generated_ids = solver_model.generate(
185
- **model_inputs,
186
- max_new_tokens=300,
187
- do_sample=False,
 
 
 
 
 
 
 
 
188
  )
189
- # Strip the prompt tokens off, keep only the newly generated continuation
190
- new_tokens = generated_ids[:, model_inputs["input_ids"].shape[1]:]
191
- raw_response = solver_tokenizer.batch_decode(new_tokens, skip_special_tokens=True)[0]
 
192
 
193
- return parse_solver_response(raw_response, options)
194
 
 
 
 
 
195
 
196
- # --- 5. AI Inference Function: OCR (Stage 1) ---
197
- @spaces.GPU
198
- def generate_mcqs(image):
199
- if image is None:
200
- raise gr.Error("Please upload an image first.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
 
202
- # Move model to GPU only when the function is called
203
- device = "cuda" if torch.cuda.is_available() else "cpu"
204
- model.to(device)
205
 
206
- # Process image
207
- inputs = processor(image, return_tensors="pt", format=True, crop_to_patches=True, max_patches=4).to(device)
 
 
 
 
 
208
 
209
- # Generate text
210
- generate_ids = model.generate(
211
- **inputs,
212
- do_sample=False,
213
- tokenizer=processor.tokenizer,
214
- stop_strings="<|im_end|>",
215
- max_new_tokens=4096,
216
- )
217
 
218
- output_text = processor.decode(
219
- generate_ids[0, inputs["input_ids"].shape[1]:],
220
- skip_special_tokens=True,
221
- )
 
 
 
 
 
 
222
 
223
- # Parse into structured data
224
- mcqs = post_process(output_text)
225
-
226
- # Safeguard: If the OCR failed to extract any questions
227
- if not mcqs:
228
- raise gr.Error("Could not detect any MCQs in the image. Try a clearer photo.")
229
-
230
- return mcqs
231
-
232
-
233
- # --- 6. AI Inference Function: Solver (Stage 2) ---
234
- @spaces.GPU(duration=120) # bump this if you expect long quizzes (many questions)
235
- def solve_mcqs_with_llm(mcqs, progress=gr.Progress()):
236
- """
237
- Takes the raw OCR'd questions and asks Qwen2.5-1.5B-Instruct to solve
238
- them ONE BY ONE, attaching the model's chosen answer + explanation to
239
- every question before the quiz is revealed.
240
- """
241
- device = "cuda" if torch.cuda.is_available() else "cpu"
242
- solver_model.to(device)
243
-
244
- solved_mcqs = []
245
- total = len(mcqs)
246
- for i, item in enumerate(mcqs):
247
- progress(i / total, desc=f"Solving question {i + 1}/{total}...")
248
- answer, explanation = ask_solver_model(item["q"], item["options"], device)
249
- solved_mcqs.append({
250
- "q": item["q"],
251
- "options": item["options"],
252
- "a": answer,
253
- "explanation": explanation,
254
- })
255
- progress(1.0, desc="Done!")
256
 
257
- first_q = solved_mcqs[0]
258
- return (
259
- solved_mcqs,
260
- 0, # reset state_idx
261
- 0, # reset state_score
262
- [], # reset state_user_answers
263
- gr.update(visible=False), # upload_row -> hide
264
- gr.update(visible=True), # quiz_row -> show
265
- gr.update(value=first_q["q"]), # question_display
266
- gr.update(choices=first_q["options"], value=None), # options_radio
267
- gr.update(value="", visible=False), # hint_display -> hidden/reset
268
- )
269
 
 
 
 
270
 
271
- # --- 7. State Management for the Quiz ---
272
- def show_hint(mcqs, current_idx):
273
- """Reveal the solver model's explanation for the current question."""
274
- if not mcqs or current_idx >= len(mcqs):
275
- return gr.update(value="No hint available.", visible=True)
276
- explanation = mcqs[current_idx].get("explanation") or "No explanation available."
277
- return gr.update(value=f"💡 **Hint:** {explanation}", visible=True)
 
 
 
 
278
 
279
 
280
- def build_results_summary(mcqs, user_answers, score):
281
- """Walk back through every question, comparing the user's pick against
282
- the solver model's answer, for the final results screen."""
283
- lines = [f"### Quiz Complete! You scored {score}/{len(mcqs)}\n"]
284
- for i, item in enumerate(mcqs):
285
- picked = user_answers[i] if i < len(user_answers) else None
286
- correct_ans = item["a"]
287
- is_correct = picked == correct_ans
288
- icon = "✅" if is_correct else "❌"
289
 
290
- lines.append(f"**{icon} Q{i + 1}. {item['q']}**")
291
- lines.append(f"- Your answer: {picked if picked else '*(no answer)*'}")
292
- if not is_correct:
293
- lines.append(f"- Correct answer: {correct_ans}")
294
- lines.append(f"- Explanation: {item.get('explanation', 'N/A')}")
295
- lines.append("")
296
 
297
- return "\n".join(lines)
 
 
 
298
 
 
 
 
299
 
300
- def handle_answer(selected_option, mcqs, current_idx, score, user_answers):
301
- # Check the user's pick against the answer the solver model settled on
302
- correct_answer = mcqs[current_idx]["a"]
303
- user_answers = user_answers + [selected_option]
 
 
 
 
 
 
 
 
 
 
 
 
304
 
305
- if selected_option == correct_answer:
306
- score += 1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
307
 
308
- current_idx += 1
309
 
310
- if current_idx >= len(mcqs):
311
- summary_md = build_results_summary(mcqs, user_answers, score)
 
 
312
  return (
313
- current_idx,
314
- score,
315
- user_answers,
316
- gr.update(visible=False), # quiz_row
317
- gr.update(visible=True), # results_row
318
- gr.update(value=summary_md), # results_display
319
- gr.update(), # question_display (no-op)
320
- gr.update(), # options_radio (no-op)
321
- gr.update(value="", visible=False), # hint_display -> reset
322
  )
323
 
324
- next_q = mcqs[current_idx]["q"]
325
- next_options = mcqs[current_idx]["options"]
326
-
327
  return (
328
- current_idx,
329
- score,
330
- user_answers,
331
  gr.update(visible=True),
332
  gr.update(visible=False),
 
 
 
333
  gr.update(),
334
- gr.update(value=next_q),
335
- gr.update(choices=next_options, value=None),
336
- gr.update(value="", visible=False), # hint_display -> reset for new question
337
  )
338
 
339
 
340
- # --- 8. The UI Layout ---
341
- with gr.Blocks() as demo:
342
- state_mcqs = gr.State([])
343
- state_idx = gr.State(0)
344
- state_score = gr.State(0)
345
- state_user_answers = gr.State([])
346
-
347
- with gr.Row(visible=True) as upload_row:
348
- with gr.Column():
349
- img_input = gr.Image(type="pil")
350
- btn_generate = gr.Button("Extract & Generate Quiz")
351
-
352
- with gr.Row(visible=False) as quiz_row:
353
- with gr.Column():
354
- question_display = gr.Markdown("### Question will appear here")
355
- options_radio = gr.Radio(choices=[], label="Select your answer")
356
- with gr.Row():
357
- btn_hint = gr.Button("💡 Hint")
358
- btn_next = gr.Button("Submit & Next")
359
- hint_display = gr.Markdown(visible=False)
360
-
361
- with gr.Row(visible=False) as results_row:
362
- results_display = gr.Markdown("### Results")
363
-
364
- # --- 9. Event Wiring ---
365
- # Stage 1 (OCR) must succeed before Stage 2 (solver) runs - .success()
366
- # only fires if generate_mcqs did not raise a gr.Error.
367
- btn_generate.click(
368
- fn=generate_mcqs,
369
- inputs=[img_input],
370
- outputs=[state_mcqs],
371
- ).success(
372
- fn=solve_mcqs_with_llm,
373
- inputs=[state_mcqs],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374
  outputs=[
375
- state_mcqs, state_idx, state_score, state_user_answers,
376
- upload_row, quiz_row, question_display, options_radio, hint_display,
 
 
 
 
 
 
377
  ],
378
  )
379
 
380
- btn_hint.click(
381
- fn=show_hint,
382
- inputs=[state_mcqs, state_idx],
383
- outputs=[hint_display],
 
 
 
 
 
 
 
 
 
384
  )
385
 
386
- btn_next.click(
387
- fn=handle_answer,
388
- inputs=[options_radio, state_mcqs, state_idx, state_score, state_user_answers],
389
  outputs=[
390
- state_idx, state_score, state_user_answers,
391
- quiz_row, results_row, results_display,
392
- question_display, options_radio, hint_display,
 
 
 
 
393
  ],
394
  )
395
 
396
  if __name__ == "__main__":
397
- demo.launch()
 
1
+ """
2
+ MCQ Quiz Solver
3
+ ================
4
+
5
+ Upload photo(s) of multiple-choice questions -> GOT-OCR-2.0 reads the text ->
6
+ Qwen2.5-1.5B-Instruct solves each question -> you get quizzed one question at
7
+ a time against the AI's answers -> a final score report.
8
+
9
+ Deploy on Hugging Face Spaces (Gradio SDK). For best performance, select
10
+ "ZeroGPU" hardware in the Space settings -- the @spaces.GPU decorator below
11
+ will then transparently borrow an A100 for each OCR / LLM call. The app also
12
+ runs (slowly) on CPU-only or a normal GPU Space with no code changes needed.
13
+ """
14
+
15
+ import re
16
+ import traceback
17
+ from typing import Dict, List, Optional, Tuple
18
+
19
  import gradio as gr
 
20
  import torch
21
+ from pydantic import BaseModel, Field
 
 
22
  from transformers import (
23
+ AutoModelForCausalLM,
24
  AutoModelForImageTextToText,
25
+ AutoProcessor,
26
  AutoTokenizer,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  )
28
 
29
+ # ---------------------------------------------------------------------------
30
+ # ZeroGPU support
31
+ # ---------------------------------------------------------------------------
32
+ # `spaces` ships automatically on every Hugging Face Space. Its @spaces.GPU
33
+ # decorator is a documented no-op outside ZeroGPU hardware, so importing it
34
+ # unconditionally is the recommended pattern and safe everywhere. We still
35
+ # fall back to a plain no-op decorator so this file also runs locally on a
36
+ # machine that doesn't have the `spaces` package installed at all.
37
+ try:
38
+ import spaces
39
+
40
+ HAS_SPACES = True
41
+ except ImportError:
42
+ HAS_SPACES = False
43
+
44
+ class _DummySpaces:
45
+ @staticmethod
46
+ def GPU(fn=None, **kwargs):
47
+ if fn is None:
48
+ def _wrap(f):
49
+ return f
50
+
51
+ return _wrap
52
+ return fn
53
+
54
+ spaces = _DummySpaces()
55
+
56
+
57
+ # ---------------------------------------------------------------------------
58
+ # Config
59
+ # ---------------------------------------------------------------------------
60
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
61
+ DTYPE = torch.bfloat16 if DEVICE == "cuda" else torch.float32
62
+
63
+ OCR_MODEL_ID = "stepfun-ai/GOT-OCR-2.0-hf"
64
+ LLM_MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"
65
+
66
+ LETTERS = ["A", "B", "C", "D", "E", "F"]
67
+
68
+
69
+ # ---------------------------------------------------------------------------
70
+ # Model loading (once, at process start)
71
+ # ---------------------------------------------------------------------------
72
+ print(f"[startup] device = {DEVICE}")
73
+ print(f"[startup] loading OCR model: {OCR_MODEL_ID} ...")
74
+
75
+ ocr_processor = AutoProcessor.from_pretrained(OCR_MODEL_ID, use_fast=True)
76
+ ocr_model = AutoModelForImageTextToText.from_pretrained(
77
+ OCR_MODEL_ID,
78
+ torch_dtype=DTYPE,
79
+ ).to(DEVICE)
80
+ ocr_model.eval()
81
+
82
+ print(f"[startup] loading LLM: {LLM_MODEL_ID} ...")
83
+
84
+ llm_tokenizer = AutoTokenizer.from_pretrained(LLM_MODEL_ID)
85
+ llm_model = AutoModelForCausalLM.from_pretrained(
86
+ LLM_MODEL_ID,
87
+ torch_dtype=DTYPE,
88
+ ).to(DEVICE)
89
+ llm_model.eval()
90
+
91
+ # Wrap the LLM once with Outlines for schema-guaranteed structured output.
92
+ # If Outlines is missing or its API doesn't match what we expect, we fall
93
+ # back to plain generation + regex parsing later on -- the app keeps working
94
+ # either way, just with slightly less reliable answer-letter extraction.
95
+ OUTLINES_AVAILABLE = False
96
+ outlines_model = None
97
+ try:
98
+ import outlines
99
+
100
+ outlines_model = outlines.from_transformers(llm_model, llm_tokenizer)
101
+ OUTLINES_AVAILABLE = True
102
+ print("[startup] Outlines structured generation enabled.")
103
+ except Exception as exc: # noqa: BLE001 - defensive, we always want a fallback
104
+ print(f"[startup] Outlines unavailable, will use fallback generation. ({exc})")
105
+
106
+
107
+ class AnswerFormat(BaseModel):
108
+ correct_option: str = Field(description="The letter of the correct option, e.g. 'A'")
109
+ explanation: str = Field(description="A very short, step-by-step explanation")
110
+
111
+
112
+ # ---------------------------------------------------------------------------
113
+ # OCR
114
+ # ---------------------------------------------------------------------------
115
+ @spaces.GPU(duration=90)
116
+ def run_ocr(image_path: str) -> str:
117
+ """Run GOT-OCR-2.0 on a single image and return formatted (markdown/LaTeX) text."""
118
+ inputs = ocr_processor(
119
+ image_path,
120
+ return_tensors="pt",
121
+ format=True,
122
+ crop_to_patches=True,
123
+ max_patches=4,
124
+ ).to(DEVICE)
125
+
126
+ with torch.no_grad():
127
+ generate_ids = ocr_model.generate(
128
+ **inputs,
129
+ do_sample=False,
130
+ tokenizer=ocr_processor.tokenizer,
131
+ stop_strings="<|im_end|>",
132
+ max_new_tokens=4096,
133
+ )
134
 
135
+ output_text = ocr_processor.decode(
136
+ generate_ids[0, inputs["input_ids"].shape[1]:],
137
+ skip_special_tokens=True,
138
+ )
139
+ return output_text
140
+
141
+
142
+ # ---------------------------------------------------------------------------
143
+ # Parsing OCR text into MCQ questions
144
+ # ---------------------------------------------------------------------------
145
+ _OPTION_RE = re.compile(r"^\(?([a-fA-F])[\)\.\:]\s*(.*)")
146
+ _QNUM_RE = re.compile(r"^\(?\d+[\)\.\:]\s*(.*)")
147
+
148
+
149
+ def parse_questions(ocr_text: str) -> List[Dict]:
150
+ """Turn raw OCR text into a list of {"question_text", "options": [...]} dicts."""
151
+ questions: List[Dict] = []
152
+ q_chunks: List[str] = []
153
+ options: List[str] = []
154
+
155
+ def flush() -> None:
156
+ nonlocal q_chunks, options
157
+ if q_chunks and options:
158
+ questions.append(
159
+ {
160
+ "question_text": " ".join(q_chunks).strip(),
161
+ "options": list(options),
162
+ }
163
+ )
164
+ q_chunks = []
165
+ options = []
166
+
167
+ for raw_line in ocr_text.splitlines():
168
+ line = raw_line.strip()
169
+ if not line:
170
+ continue
171
 
172
+ opt_match = _OPTION_RE.match(line)
173
+ if opt_match:
174
+ options.append(opt_match.group(2).strip())
175
+ continue
176
 
177
+ # Hitting a non-option line after we've started collecting options
178
+ # means the previous question block is complete -- save it.
179
+ if options:
180
+ flush()
181
 
182
+ q_match = _QNUM_RE.match(line)
183
+ if q_match:
184
+ line = q_match.group(1).strip()
185
 
186
+ q_chunks.append(line)
 
 
 
 
 
 
 
187
 
188
+ flush()
189
+ return questions
190
 
 
 
191
 
192
+ # ---------------------------------------------------------------------------
193
+ # LLM answer generation
194
+ # ---------------------------------------------------------------------------
195
+ def _build_prompt(question_text: str, options: List[str]) -> str:
196
+ lines = [f"Question: {question_text}"]
197
+ for i, opt in enumerate(options):
198
+ label = LETTERS[i] if i < len(LETTERS) else str(i)
199
+ lines.append(f"{label}) {opt}")
200
+ lines.append(
201
+ "\nAnalyze the question and respond with the correct option letter "
202
+ "and a very short explanation."
203
+ )
204
+ raw_content = "\n".join(lines)
205
 
206
+ if getattr(llm_tokenizer, "chat_template", None):
207
+ return llm_tokenizer.apply_chat_template(
208
+ [{"role": "user", "content": raw_content}],
209
+ tokenize=False,
210
+ add_generation_prompt=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
211
  )
212
+ return raw_content
213
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
214
 
215
+ def _fallback_answer(prompt: str) -> Tuple[str, str]:
216
+ """Plain generation + regex extraction, used if Outlines isn't usable."""
217
+ inputs = llm_tokenizer(prompt, return_tensors="pt").to(DEVICE)
218
+ with torch.no_grad():
219
+ output_ids = llm_model.generate(
220
+ **inputs,
221
+ max_new_tokens=400,
222
+ do_sample=False,
223
+ )
224
+ text = llm_tokenizer.decode(
225
+ output_ids[0, inputs["input_ids"].shape[1]:],
226
+ skip_special_tokens=True,
227
  )
228
+ match = re.search(r"\b([A-F])\b", text.upper())
229
+ letter = match.group(1) if match else "A"
230
+ explanation = text.strip()[:400] or "No explanation generated."
231
+ return letter, explanation
232
 
 
233
 
234
+ @spaces.GPU(duration=45)
235
+ def generate_ai_answer(question_text: str, options: List[str]) -> Tuple[str, str]:
236
+ """Return (correct_option_letter, explanation) for one MCQ."""
237
+ prompt = _build_prompt(question_text, options)
238
 
239
+ if OUTLINES_AVAILABLE:
240
+ try:
241
+ result = outlines_model(prompt, AnswerFormat, max_new_tokens=400)
242
+ # Depending on the installed Outlines version this may already be
243
+ # a parsed AnswerFormat instance, or a raw JSON string -- handle both.
244
+ if isinstance(result, AnswerFormat):
245
+ parsed = result
246
+ elif isinstance(result, str):
247
+ parsed = AnswerFormat.model_validate_json(result)
248
+ else:
249
+ parsed = AnswerFormat.model_validate(result)
250
+ letter = re.sub(r"[^A-Fa-f]", "", parsed.correct_option).upper()[:1] or "A"
251
+ return letter, parsed.explanation
252
+ except Exception as exc: # noqa: BLE001
253
+ print(f"[warn] Outlines generation failed, falling back: {exc}")
254
+
255
+ return _fallback_answer(prompt)
256
+
257
+
258
+ def process_single_image(
259
+ image_path: str,
260
+ progress: Optional[gr.Progress],
261
+ img_idx: int,
262
+ total_imgs: int,
263
+ ) -> List[Dict]:
264
+ ocr_text = run_ocr(image_path)
265
+ questions = parse_questions(ocr_text)
266
+
267
+ for qi, q in enumerate(questions):
268
+ if progress is not None:
269
+ frac = (img_idx + (qi / max(len(questions), 1))) / max(total_imgs, 1)
270
+ progress(
271
+ frac,
272
+ desc=f"Image {img_idx + 1}/{total_imgs}: solving question {qi + 1}/{len(questions)}",
273
+ )
274
+ letter, explanation = generate_ai_answer(q["question_text"], q["options"])
275
+ q["ai_answer"] = letter
276
+ q["ai_explanation"] = explanation
277
+
278
+ return questions
279
+
280
+
281
+ def run_pipeline(image_paths: List[str], progress: gr.Progress) -> List[Dict]:
282
+ if not image_paths:
283
+ raise gr.Error("Please upload at least one image before processing.")
284
+
285
+ all_questions: List[Dict] = []
286
+ total = len(image_paths)
287
+ for i, path in enumerate(image_paths):
288
+ progress(i / total, desc=f"Reading image {i + 1} of {total}...")
289
+ try:
290
+ qs = process_single_image(path, progress, i, total)
291
+ except Exception as exc: # noqa: BLE001
292
+ traceback.print_exc()
293
+ raise gr.Error(f"Failed to process image {i + 1}: {exc}") from exc
294
+ all_questions.extend(qs)
295
 
296
+ progress(1.0, desc="Done!")
 
 
297
 
298
+ if not all_questions:
299
+ raise gr.Error(
300
+ "No multiple-choice questions were detected. Please make sure the "
301
+ "image(s) show clearly readable text with lettered options like "
302
+ "a), b), c)..."
303
+ )
304
+ return all_questions
305
 
 
 
 
 
 
 
 
 
306
 
307
+ # ---------------------------------------------------------------------------
308
+ # Gradio callbacks
309
+ # ---------------------------------------------------------------------------
310
+ def _extract_paths(files) -> List[str]:
311
+ if not files:
312
+ return []
313
+ paths = []
314
+ for f in files:
315
+ paths.append(f if isinstance(f, str) else getattr(f, "name", None))
316
+ return [p for p in paths if p]
317
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
 
319
+ def start_quiz(files, progress=gr.Progress()):
320
+ image_paths = _extract_paths(files)
321
+ questions = run_pipeline(image_paths, progress)
 
 
 
 
 
 
 
 
 
322
 
323
+ first_q = questions[0]
324
+ choices = [f"{LETTERS[i]}) {opt}" for i, opt in enumerate(first_q["options"])]
325
+ progress_text = f"**Question 1 of {len(questions)}**"
326
 
327
+ return (
328
+ questions, # questions_state
329
+ 0, # idx_state
330
+ [], # answers_state
331
+ gr.update(visible=False), # upload_group
332
+ gr.update(visible=True), # quiz_group
333
+ gr.update(visible=False), # report_group
334
+ progress_text, # progress_md
335
+ first_q["question_text"], # question_md
336
+ gr.update(choices=choices, value=None), # options_radio
337
+ )
338
 
339
 
340
+ def _normalize_letter(value) -> Optional[str]:
341
+ if not value:
342
+ return None
343
+ match = re.search(r"[A-Fa-f]", str(value))
344
+ return match.group(0).upper() if match else None
 
 
 
 
345
 
 
 
 
 
 
 
346
 
347
+ def build_report(questions: List[Dict], answers: List[Optional[str]]) -> str:
348
+ total = len(questions)
349
+ correct = wrong = skipped = 0
350
+ rows = []
351
 
352
+ for i, q in enumerate(questions):
353
+ user_ans = answers[i] if i < len(answers) else None
354
+ ai_letter = _normalize_letter(q.get("ai_answer"))
355
 
356
+ if user_ans is None:
357
+ skipped += 1
358
+ result = "⏭️ Skipped"
359
+ user_letter = None
360
+ else:
361
+ user_letter = _normalize_letter(user_ans)
362
+ if ai_letter and user_letter == ai_letter:
363
+ correct += 1
364
+ result = "✅ Correct"
365
+ else:
366
+ wrong += 1
367
+ result = "❌ Wrong"
368
+
369
+ rows.append(
370
+ f"| {i + 1} | {result} | {user_letter or '-'} | {ai_letter or '-'} |"
371
+ )
372
 
373
+ score_pct = (correct / total * 100) if total else 0.0
374
+
375
+ header = (
376
+ "## 🎉 Quiz Complete!\n\n"
377
+ "| Metric | Value |\n"
378
+ "|---|---|\n"
379
+ f"| Total Questions | {total} |\n"
380
+ f"| ✅ Correctly Solved | {correct} |\n"
381
+ f"| ❌ Wrong | {wrong} |\n"
382
+ f"| ⏭️ Skipped | {skipped} |\n"
383
+ f"| **Final Score** | **{score_pct:.1f}%** |\n\n"
384
+ "### Question-by-question breakdown\n\n"
385
+ "| # | Result | Your answer | AI answer |\n"
386
+ "|---|---|---|---|\n"
387
+ )
388
+ return header + "\n".join(rows)
389
 
 
390
 
391
+ def _advance(questions: List[Dict], idx: int, answers: List[Optional[str]]):
392
+ new_idx = idx + 1
393
+ if new_idx >= len(questions):
394
+ report = build_report(questions, answers)
395
  return (
396
+ new_idx, # idx_state
397
+ answers, # answers_state
398
+ gr.update(visible=False), # quiz_group
399
+ gr.update(visible=True), # report_group
400
+ gr.update(), # progress_md (unchanged)
401
+ gr.update(), # question_md (unchanged)
402
+ gr.update(), # options_radio (unchanged)
403
+ report, # report_md
 
404
  )
405
 
406
+ q = questions[new_idx]
407
+ choices = [f"{LETTERS[i]}) {opt}" for i, opt in enumerate(q["options"])]
408
+ progress_text = f"**Question {new_idx + 1} of {len(questions)}**"
409
  return (
410
+ new_idx,
411
+ answers,
 
412
  gr.update(visible=True),
413
  gr.update(visible=False),
414
+ progress_text,
415
+ q["question_text"],
416
+ gr.update(choices=choices, value=None),
417
  gr.update(),
 
 
 
418
  )
419
 
420
 
421
+ def submit_answer(selected, questions, idx, answers):
422
+ if not selected:
423
+ raise gr.Error("Please select an option, or click 'Skip Question' if you're unsure.")
424
+ letter = selected.split(")")[0].strip().upper()
425
+ return _advance(questions, idx, answers + [letter])
426
+
427
+
428
+ def skip_question(questions, idx, answers):
429
+ return _advance(questions, idx, answers + [None])
430
+
431
+
432
+ def restart_quiz():
433
+ return (
434
+ [], # questions_state
435
+ 0, # idx_state
436
+ [], # answers_state
437
+ gr.update(visible=True), # upload_group
438
+ gr.update(visible=False), # quiz_group
439
+ gr.update(visible=False), # report_group
440
+ None, # image_input
441
+ )
442
+
443
+
444
+ # ---------------------------------------------------------------------------
445
+ # UI
446
+ # ---------------------------------------------------------------------------
447
+ with gr.Blocks(title="MCQ Quiz Solver", theme=gr.themes.Soft()) as demo:
448
+ questions_state = gr.State([])
449
+ idx_state = gr.State(0)
450
+ answers_state = gr.State([])
451
+
452
+ gr.Markdown(
453
+ "# 📝 MCQ Quiz Solver\n"
454
+ "Upload photo(s) of multiple-choice questions. An OCR model reads them, "
455
+ "an AI model solves them, and then you get quizzed against the AI's answers."
456
+ )
457
+
458
+ with gr.Group(visible=True) as upload_group:
459
+ image_input = gr.File(
460
+ label="Upload one or more question images",
461
+ file_count="multiple",
462
+ file_types=["image"],
463
+ )
464
+ process_btn = gr.Button("Process Images & Start Quiz", variant="primary")
465
+ gr.Markdown(
466
+ "*The first run can take a while while the models load. Works best "
467
+ "with clear, well-lit photos where options are labeled a), b), c)...*"
468
+ )
469
+
470
+ with gr.Group(visible=False) as quiz_group:
471
+ progress_md = gr.Markdown()
472
+ question_md = gr.Markdown()
473
+ options_radio = gr.Radio(label="Choose your answer", choices=[])
474
+ with gr.Row():
475
+ skip_btn = gr.Button("⏭️ Skip Question")
476
+ next_btn = gr.Button("Submit & Next ➡️", variant="primary")
477
+
478
+ with gr.Group(visible=False) as report_group:
479
+ report_md = gr.Markdown()
480
+ restart_btn = gr.Button("🔁 Start New Quiz", variant="primary")
481
+
482
+ process_btn.click(
483
+ fn=start_quiz,
484
+ inputs=[image_input],
485
+ outputs=[
486
+ questions_state,
487
+ idx_state,
488
+ answers_state,
489
+ upload_group,
490
+ quiz_group,
491
+ report_group,
492
+ progress_md,
493
+ question_md,
494
+ options_radio,
495
+ ],
496
+ )
497
+
498
+ next_btn.click(
499
+ fn=submit_answer,
500
+ inputs=[options_radio, questions_state, idx_state, answers_state],
501
  outputs=[
502
+ idx_state,
503
+ answers_state,
504
+ quiz_group,
505
+ report_group,
506
+ progress_md,
507
+ question_md,
508
+ options_radio,
509
+ report_md,
510
  ],
511
  )
512
 
513
+ skip_btn.click(
514
+ fn=skip_question,
515
+ inputs=[questions_state, idx_state, answers_state],
516
+ outputs=[
517
+ idx_state,
518
+ answers_state,
519
+ quiz_group,
520
+ report_group,
521
+ progress_md,
522
+ question_md,
523
+ options_radio,
524
+ report_md,
525
+ ],
526
  )
527
 
528
+ restart_btn.click(
529
+ fn=restart_quiz,
530
+ inputs=[],
531
  outputs=[
532
+ questions_state,
533
+ idx_state,
534
+ answers_state,
535
+ upload_group,
536
+ quiz_group,
537
+ report_group,
538
+ image_input,
539
  ],
540
  )
541
 
542
  if __name__ == "__main__":
543
+ demo.queue().launch()
requirements.txt CHANGED
@@ -1,6 +1,10 @@
1
- gradio
 
 
 
2
  torch
3
- transformers
4
  pillow
5
- pydantic
6
- torchvision
 
 
 
1
+ gradio>=5.0.0
2
+ spaces
3
+ transformers>=4.49.0
4
+ accelerate>=0.26.0
5
  torch
 
6
  pillow
7
+ pydantic>=2.0
8
+ outlines>=0.1.0
9
+ sentencepiece
10
+ protobuf