pawanmakes commited on
Commit
bc2af72
·
1 Parent(s): f56945a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +356 -58
app.py CHANGED
@@ -1,99 +1,397 @@
1
  import gradio as gr
2
- import spaces # <-- 1. Import spaces
3
  import torch
 
 
 
 
 
 
 
 
 
 
 
4
 
5
- # --- 1. Your AI Integration Here ---
6
- @spaces.GPU # <-- 2. Apply this to the function doing the heavy lifting
7
- def generate_mcqs(image):
8
- # Your actual model inference goes here.
9
- # Because of the decorator, any tensors you move to '.cuda()' in here will work.
10
-
11
- # Mock data for demonstration
12
- mock_mcqs = [
13
- {"q": "What is the main object in this image?", "options": ["Car", "Dog", "Tree", "House"], "a": "Dog"},
14
- {"q": "What color is the sky?", "options": ["Blue", "Red", "Green", "Yellow"], "a": "Blue"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  ]
16
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  return (
18
- mock_mcqs,
19
- 0,
20
- 0,
21
- gr.update(visible=False),
22
- gr.update(visible=True),
23
- mock_mcqs[0]["q"],
24
- gr.update(choices=mock_mcqs[0]["options"], value=None)
 
 
25
  )
26
 
27
- # --- 2. State Management for the Quiz ---
28
- def handle_answer(selected_option, mcqs, current_idx, score):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  correct_answer = mcqs[current_idx]["a"]
 
 
30
  if selected_option == correct_answer:
31
  score += 1
32
-
33
  current_idx += 1
34
-
35
- # Check if quiz is over
36
  if current_idx >= len(mcqs):
37
- final_msg = f"Quiz Complete! You scored {score}/{len(mcqs)}."
38
  return (
39
- current_idx,
40
- score,
41
- gr.update(visible=False), # Hide quiz_row
42
- gr.update(visible=True), # Show results_row
43
- gr.update(value=final_msg), # <-- 3. Update the text of results_display
44
- gr.update(),
45
- gr.update()
 
 
46
  )
47
-
48
- # Load next question
49
  next_q = mcqs[current_idx]["q"]
50
  next_options = mcqs[current_idx]["options"]
51
-
52
  return (
53
- current_idx,
54
- score,
55
- gr.update(visible=True), # Keep quiz_row visible
56
- gr.update(visible=False), # Keep results_row hidden
57
- gr.update(), # Don't change results_display yet
58
- gr.update(value=next_q), # Update question_display
59
- gr.update(choices=next_options, value=None) # Update options_radio
 
 
60
  )
61
 
62
- # --- 3. The UI Layout ---
 
63
  with gr.Blocks() as demo:
64
  state_mcqs = gr.State([])
65
  state_idx = gr.State(0)
66
  state_score = gr.State(0)
 
67
 
68
- # Phase 1: Upload Layout
69
  with gr.Row(visible=True) as upload_row:
70
  with gr.Column():
71
  img_input = gr.Image(type="pil")
72
- btn_generate = gr.Button("Generate Quiz")
73
-
74
- # Phase 2: Quiz Layout
75
  with gr.Row(visible=False) as quiz_row:
76
  with gr.Column():
77
  question_display = gr.Markdown("### Question will appear here")
78
  options_radio = gr.Radio(choices=[], label="Select your answer")
79
- btn_next = gr.Button("Submit & Next")
80
-
81
- # Phase 3: Results Layout
 
 
82
  with gr.Row(visible=False) as results_row:
83
- results_display = gr.Markdown("### Results") # <-- 4. This is what we target with the final text
84
 
85
- # --- 4. Event Wiring ---
 
 
86
  btn_generate.click(
87
  fn=generate_mcqs,
88
  inputs=[img_input],
89
- outputs=[state_mcqs, state_idx, state_score, upload_row, quiz_row, question_display, options_radio]
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  )
91
-
92
  btn_next.click(
93
  fn=handle_answer,
94
- inputs=[options_radio, state_mcqs, state_idx, state_score],
95
- # Notice we added results_display to the outputs here to receive the final message
96
- outputs=[state_idx, state_score, quiz_row, results_row, results_display, question_display, options_radio]
 
 
 
97
  )
98
 
99
- demo.launch()
 
 
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()