atz21 commited on
Commit
8bef227
Β·
verified Β·
1 Parent(s): 7884d2d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +324 -76
app.py CHANGED
@@ -2,16 +2,18 @@ import os
2
  import re
3
  import json
4
  import subprocess
5
- import cv2
6
- import numpy as np
7
  import img2pdf
8
  import gradio as gr
9
  import google.generativeai as genai
10
  from markdown_pdf import MarkdownPdf, Section
11
  from pdf2image import convert_from_path
12
- from PIL import Image
 
 
13
 
14
- # ---------- PROMPTS ----------
15
  PROMPTS = {
16
  "ALIGNMENT_PROMPT": {
17
  "role": "system",
@@ -88,9 +90,11 @@ Then show total clearly:
88
  }
89
 
90
  # -------------------- CONFIG --------------------
 
91
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
92
 
93
- GRID_ROWS, GRID_COLS = 20, 14 # grid for imprint placement
 
94
 
95
  # ---------- HELPERS ----------
96
  def save_as_pdf(text, filename="output.pdf"):
@@ -100,14 +104,24 @@ def save_as_pdf(text, filename="output.pdf"):
100
  return filename
101
 
102
  def compress_pdf(input_path, output_path=None, max_size=20*1024*1024):
103
- """Compress PDF only if larger than max_size (20MB default)."""
 
 
 
104
  if output_path is None:
105
  base, ext = os.path.splitext(input_path)
106
  output_path = f"{base}_compressed{ext}"
107
 
108
- if os.path.getsize(input_path) <= max_size:
 
 
 
 
 
 
109
  return input_path
110
 
 
111
  try:
112
  gs_cmd = [
113
  "gs", "-sDEVICE=pdfwrite",
@@ -117,120 +131,341 @@ def compress_pdf(input_path, output_path=None, max_size=20*1024*1024):
117
  f"-sOutputFile={output_path}", input_path
118
  ]
119
  subprocess.run(gs_cmd, check=True)
120
- if os.path.getsize(output_path) <= max_size:
 
 
121
  return output_path
122
  else:
 
123
  return input_path
124
- except Exception:
 
125
  return input_path
126
 
127
  def create_model():
128
  try:
 
129
  return genai.GenerativeModel("gemini-2.5-pro", generation_config={"temperature": 0})
130
  except Exception:
 
131
  return genai.GenerativeModel("gemini-2.5-flash", generation_config={"temperature": 0})
132
 
133
- # ---------- Extract marks per question ----------
134
  def extract_marks_from_grading(grading_text):
 
 
 
 
135
  grading_json = {"grading": []}
136
- # Split by question sections
137
- question_blocks = re.split(r"## Question\s+", grading_text)
138
- for block in question_blocks[1:]: # skip intro
139
- # Extract question ID (like "1(a)" or "2.b")
140
- q_match = re.match(r"([\d\.a-zA-Z\(\)]+)", block.strip())
141
- if not q_match:
142
- continue
143
- q_id = q_match.group(1).strip()
144
-
145
- # Find awarded marks in that block
 
 
 
 
 
 
 
146
  awarded = re.findall(r"\b(M\d+|A\d+|R\d+|M0|A0|R0)\b", block)
 
 
 
 
 
 
 
147
 
148
  grading_json["grading"].append({
149
  "question": q_id,
150
- "marks_awarded": awarded
151
  })
152
 
153
  return grading_json
154
 
155
- # ---------- Imprinting Logic ----------
156
- def imprint_marks(pdf_path, grading_json, output_pdf):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
  pages = convert_from_path(pdf_path, dpi=200)
158
- annotated_pages = []
159
-
160
- for idx, page in enumerate(pages):
161
- img = np.array(page.convert("RGB"))
162
- img = cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
163
-
164
- y_offset = 100 # baseline vertical offset
165
- for g in grading_json["grading"]:
166
- marks_text = ",".join(g["marks_awarded"])
167
- # Simple placement: stack vertically
168
- cv2.putText(img, f"{g['question']}: {marks_text}",
169
- (50, y_offset),
170
- cv2.FONT_HERSHEY_SIMPLEX,
171
- 1.2, (0, 0, 255), 3, cv2.LINE_AA)
172
- y_offset += 50
173
-
174
- annotated_path = f"annotated_{idx+1}.png"
175
- cv2.imwrite(annotated_path, img)
176
- annotated_pages.append(annotated_path)
177
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  with open(output_pdf, "wb") as f:
179
- f.write(img2pdf.convert(annotated_pages))
180
-
181
- return compress_pdf(output_pdf)
182
-
183
- # ---------- PIPELINE ----------
184
- def align_and_grade(qp_file, ms_file, ans_file, imprint=False):
 
 
 
 
 
 
 
 
 
 
185
  try:
186
- # Compress only if >20MB
187
- qp_file = compress_pdf(qp_file, "qp_compressed.pdf")
188
- ms_file = compress_pdf(ms_file, "ms_compressed.pdf")
189
- ans_file = compress_pdf(ans_file, "ans_compressed.pdf")
190
 
191
- qp_uploaded = genai.upload_file(path=qp_file, display_name="Question Paper")
192
- ms_uploaded = genai.upload_file(path=ms_file, display_name="Markscheme")
193
- ans_uploaded = genai.upload_file(path=ans_file, display_name="Answer Sheet")
 
 
194
 
195
  model = create_model()
196
 
197
- # ---- Step 1: ALIGN (JSON only)
 
198
  resp = model.generate_content([
199
  PROMPTS["ALIGNMENT_PROMPT"]["content"],
200
  qp_uploaded,
201
  ms_uploaded,
202
  ans_uploaded
203
  ])
 
204
  json_output = getattr(resp, "text", None)
205
- if not json_output and resp.candidates:
206
  json_output = resp.candidates[0].content.parts[0].text
207
 
208
- # ---- Step 2: GRADING (Markdown)
 
 
 
 
 
 
 
 
209
  response = model.generate_content([
210
  PROMPTS["GRADING_PROMPT"]["content"],
211
  json_output
212
  ])
213
- grading = getattr(response, "text", None)
214
- if not grading and response.candidates:
215
- grading = response.candidates[0].content.parts[0].text
216
 
217
- base_name = os.path.splitext(os.path.basename(ans_file))[0]
218
- grading_pdf_path = save_as_pdf(grading, f"{base_name}_graded.pdf")
219
 
220
- # ---- Step 3 (Optional): Imprint marks on answer PDF ----
221
- imprint_pdf_path = None
 
 
 
 
 
 
 
 
 
 
 
 
222
  if imprint:
223
- grading_json = extract_marks_from_grading(grading)
224
- imprint_pdf_path = imprint_marks(ans_file, grading_json, f"{base_name}_imprinted.pdf")
 
 
 
225
 
226
- return json_output, grading, grading_pdf_path, imprint_pdf_path
227
 
228
  except Exception as e:
 
229
  return f"❌ Error: {e}", None, None, None
230
 
231
  # ---------- GRADIO APP ----------
232
  with gr.Blocks(title="LeadIB AI Grading (Alignment + Auto-Grading + Imprint)") as demo:
233
- gr.Markdown("## πŸ“˜ LeadIB AI Grading\nUpload **Question Paper**, **Markscheme**, and **Student Answer Sheet**.\nSystem aligns β†’ grades β†’ optionally imprints marks.")
234
 
235
  with gr.Row():
236
  qp_file = gr.File(label="πŸ“„ Upload Question Paper (PDF)")
@@ -241,16 +476,29 @@ with gr.Blocks(title="LeadIB AI Grading (Alignment + Auto-Grading + Imprint)") a
241
  run_button = gr.Button("πŸš€ Run Alignment + Grading")
242
 
243
  with gr.Row():
244
- json_output = gr.Textbox(label="πŸ“‘ Step 1: Alignment (JSON)", lines=20)
245
- grading_output = gr.Textbox(label="πŸ“ Step 2: Grading (Markdown)", lines=20)
 
 
 
 
 
 
 
 
 
 
 
 
 
246
 
247
- grading_pdf = gr.File(label="πŸ“₯ Download Grading PDF")
248
- imprint_pdf = gr.File(label="πŸ“₯ Download Imprinted PDF (Optional)")
249
 
250
  run_button.click(
251
- fn=align_and_grade,
252
  inputs=[qp_file, ms_file, ans_file, imprint_toggle],
253
- outputs=[json_output, grading_output, grading_pdf, imprint_pdf]
254
  )
255
 
256
  if __name__ == "__main__":
 
2
  import re
3
  import json
4
  import subprocess
5
+ import tempfile
6
+ import time
7
  import img2pdf
8
  import gradio as gr
9
  import google.generativeai as genai
10
  from markdown_pdf import MarkdownPdf, Section
11
  from pdf2image import convert_from_path
12
+ from PIL import Image, ImageDraw, ImageFont
13
+ import cv2
14
+ import numpy as np
15
 
16
+ # ---------- PROMPTS (preserved exactly) ----------
17
  PROMPTS = {
18
  "ALIGNMENT_PROMPT": {
19
  "role": "system",
 
90
  }
91
 
92
  # -------------------- CONFIG --------------------
93
+ # The Gemini API key must be set in the environment
94
  genai.configure(api_key=os.getenv("GEMINI_API_KEY"))
95
 
96
+ # Grid config for imprinting
97
+ GRID_ROWS, GRID_COLS = 20, 14
98
 
99
  # ---------- HELPERS ----------
100
  def save_as_pdf(text, filename="output.pdf"):
 
104
  return filename
105
 
106
  def compress_pdf(input_path, output_path=None, max_size=20*1024*1024):
107
+ """
108
+ Compress PDF only if its size is larger than max_size (default 20MB).
109
+ Returns path to (possibly compressed) file.
110
+ """
111
  if output_path is None:
112
  base, ext = os.path.splitext(input_path)
113
  output_path = f"{base}_compressed{ext}"
114
 
115
+ try:
116
+ size = os.path.getsize(input_path)
117
+ except Exception:
118
+ return input_path
119
+
120
+ if size <= max_size:
121
+ print(f"ℹ️ Not compressing {input_path} ({size/1024/1024:.2f} MB <= {max_size/1024/1024} MB)")
122
  return input_path
123
 
124
+ print(f"πŸ”Ž Compressing {input_path} ({size/1024/1024:.2f} MB) -> {output_path}")
125
  try:
126
  gs_cmd = [
127
  "gs", "-sDEVICE=pdfwrite",
 
131
  f"-sOutputFile={output_path}", input_path
132
  ]
133
  subprocess.run(gs_cmd, check=True)
134
+ new_size = os.path.getsize(output_path)
135
+ print(f"βœ… Compression done. New size: {new_size/1024/1024:.2f} MB")
136
+ if new_size <= max_size:
137
  return output_path
138
  else:
139
+ print("⚠️ Compressed file still larger than threshold; returning original")
140
  return input_path
141
+ except Exception as e:
142
+ print("❌ Compression error:", e)
143
  return input_path
144
 
145
  def create_model():
146
  try:
147
+ print("⚑ Using gemini-2.5-pro model")
148
  return genai.GenerativeModel("gemini-2.5-pro", generation_config={"temperature": 0})
149
  except Exception:
150
+ print("⚑ Falling back to gemini-2.5-flash model")
151
  return genai.GenerativeModel("gemini-2.5-flash", generation_config={"temperature": 0})
152
 
153
+ # ---------- Extract marks per question (parse grading Markdown) ----------
154
  def extract_marks_from_grading(grading_text):
155
+ """
156
+ Parse the grading markdown produced by the GRADING_PROMPT and extract marks per question.
157
+ Returns dict: {"grading": [{"question": "1.a", "marks_awarded": ["M1","A1"]}, ...]}
158
+ """
159
  grading_json = {"grading": []}
160
+
161
+ # Split by question sections using "## Question" header
162
+ # We allow various header spacing, e.g. "## Question 1(a)" or "## Question 1(a)\n..."
163
+ question_blocks = re.split(r"##\s*Question\s+", grading_text)
164
+ for block in question_blocks[1:]: # skip anything before first question header
165
+ # The first token up to newline is the question id line, e.g. "1(a)\n### Markscheme..."
166
+ first_line = block.strip().splitlines()[0].strip()
167
+ # Extract the question id - keep typical formats like 1, 1(a), 2.b, 3.d(ii)
168
+ q_id_match = re.match(r"([0-9]+(?:[a-zA-Z]|\([^\)]+\)|(?:\.[a-zA-Z0-9]+))*)", first_line)
169
+ if not q_id_match:
170
+ # fallback: try to extract tokens until first space
171
+ q_id = first_line.split()[0]
172
+ else:
173
+ q_id = q_id_match.group(1).strip()
174
+
175
+ # Now find all awarded marks in that block. Search the "Awarded" column entries like M1, A1, A0, R1 etc.
176
+ # We use a word-boundary regex to capture tokens.
177
  awarded = re.findall(r"\b(M\d+|A\d+|R\d+|M0|A0|R0)\b", block)
178
+ # Deduplicate preserving order
179
+ seen = set()
180
+ awarded_unique = []
181
+ for m in awarded:
182
+ if m not in seen:
183
+ awarded_unique.append(m)
184
+ seen.add(m)
185
 
186
  grading_json["grading"].append({
187
  "question": q_id,
188
+ "marks_awarded": awarded_unique
189
  })
190
 
191
  return grading_json
192
 
193
+ # ---------- Ask Gemini for mapping for one page image ----------
194
+ def ask_gemini_for_mapping_for_page(model, image_path, grading_json, rows=GRID_ROWS, cols=GRID_COLS):
195
+ """
196
+ Sends a page image and grading JSON to Gemini asking for cell numbers for questions.
197
+ Returns a list like: [{"question": "1.a", "cell_number": 23}, ...]
198
+ """
199
+ prompt = f"""
200
+ You are an exam marker. Your role is to identify where each question begins on the page.
201
+ The page is divided into a {rows} x {cols} grid. Each cell has a RUNNING NUMBER label (1..{rows*cols}).
202
+ For each question in the grading JSON, return the cell NUMBER where the FIRST STEP of that question begins.
203
+
204
+ IMPORTANT RULES:
205
+ - Do not place marks inside another question's answer area.
206
+ - Prefer placing the marks in a BLANK cell immediately to the RIGHT of the answer step. If no blank cell is available to the right, then place in a blank cell to the LEFT.
207
+ - Never place marks above or below the answer.
208
+ - If a question starts on a previous page, you may omit it for this page.
209
+ Return JSON only, like:
210
+ [{{"question": "1.a", "cell_number": 15}}, ...]
211
+
212
+ Grading JSON:
213
+ {json.dumps(grading_json, indent=2)}
214
+ """
215
+ # Load image file
216
+ img = Image.open(image_path)
217
+ # Send both prompt and image to Gemini
218
+ response = model.generate_content([prompt, img])
219
+ raw_text = getattr(response, "text", None)
220
+ if not raw_text and getattr(response, "candidates", None):
221
+ raw_text = response.candidates[0].content.parts[0].text
222
+
223
+ print("πŸ”Ž Gemini mapping raw output (page):")
224
+ print(raw_text)
225
+
226
+ # Try to extract JSON from response
227
+ # Commonly model will return JSON; attempt to parse the first JSON array/list block
228
+ json_part = None
229
+ try:
230
+ # naive: find first '[' and last ']' and json.loads
231
+ start = raw_text.index('[')
232
+ end = raw_text.rindex(']') + 1
233
+ json_part = raw_text[start:end]
234
+ mapping = json.loads(json_part)
235
+ return mapping
236
+ except Exception as e:
237
+ print("⚠️ Failed to parse mapping JSON directly:", e)
238
+ # try to find 'json\n{...}\n' patterns
239
+ match = re.search(r'(\[.*\])', raw_text, re.DOTALL)
240
+ if match:
241
+ try:
242
+ mapping = json.loads(match.group(1))
243
+ return mapping
244
+ except Exception as e2:
245
+ print("⚠️ Second parse attempt failed:", e2)
246
+ # fallback empty list
247
+ return []
248
+
249
+ # ---------- Imprinting Logic (uses mapping) ----------
250
+ def imprint_marks_using_mapping(pdf_path, grading_json, output_pdf, model, rows=GRID_ROWS, cols=GRID_COLS):
251
+ """
252
+ Convert PDF to images, create grid-numbered images, ask Gemini for mapping per page,
253
+ and then annotate marks beside the mapped cells.
254
+ Returns path to final imprinted (and possibly compressed) PDF.
255
+ Prints imprint steps in console for each page/question.
256
+ """
257
  pages = convert_from_path(pdf_path, dpi=200)
258
+ annotated_page_paths = []
259
+ print(f"πŸ“„ Converted answer PDF to {len(pages)} page image(s) for imprinting.")
260
+
261
+ # create grid-numbered temporary images for sending to Gemini
262
+ temp_grid_images = []
263
+ for p_index, page in enumerate(pages):
264
+ img = page.convert("RGB")
265
+ w, h = img.size
266
+ cell_w, cell_h = w / cols, h / rows
267
+
268
+ draw = ImageDraw.Draw(img)
269
+ try:
270
+ num_font = ImageFont.truetype("arial.ttf", 16)
271
+ except Exception:
272
+ num_font = ImageFont.load_default()
273
+
274
+ cell_num = 1
275
+ # We only need numbers for clarity when sending to model (but we won't draw gridlines)
276
+ for r in range(rows):
277
+ for c in range(cols):
278
+ x = int(c * cell_w + cell_w / 2)
279
+ y = int(r * cell_h + cell_h / 2)
280
+ text = str(cell_num)
281
+ bbox = draw.textbbox((0, 0), text, font=num_font)
282
+ tw = bbox[2] - bbox[0]
283
+ th = bbox[3] - bbox[1]
284
+ draw.text((x - tw/2, y - th/2), text, fill="black", font=num_font)
285
+ cell_num += 1
286
+
287
+ temp_path = f"page_{p_index+1}_grid.png"
288
+ img.save(temp_path, "PNG")
289
+ temp_grid_images.append(temp_path)
290
+
291
+ # Now for each page, ask Gemini for mapping
292
+ for p_index, grid_img_path in enumerate(temp_grid_images):
293
+ print(f"\nπŸ›° Sending page {p_index+1} to Gemini for mapping...")
294
+ mapping = ask_gemini_for_mapping_for_page(model, grid_img_path, grading_json, rows, cols)
295
+ print(f"πŸ” Parsed mapping for page {p_index+1}: {mapping}")
296
+
297
+ # Prepare a clean copy of the original page to annotate (no grid numbers)
298
+ page_img = pages[p_index].convert("RGB")
299
+ img_cv = np.array(page_img)
300
+ img_cv = cv2.cvtColor(img_cv, cv2.COLOR_RGB2BGR)
301
+ h, w, _ = img_cv.shape
302
+ cell_w_px, cell_h_px = w / cols, h / rows
303
+
304
+ # We will maintain a set of occupied cells to prefer right/left placement heuristics
305
+ occupied = set()
306
+
307
+ # For each mapping entry, place the corresponding marks
308
+ for item in mapping:
309
+ qid = item.get("question")
310
+ cell_number = item.get("cell_number")
311
+ if qid is None or cell_number is None:
312
+ continue
313
+
314
+ # Find marks for this question from grading_json
315
+ marks_list = next((g["marks_awarded"] for g in grading_json.get("grading", []) if g["question"] == qid), [])
316
+ if not marks_list:
317
+ # possible the grading JSON uses slightly different formatting of q ids; try case-insensitive match
318
+ marks_list = next((g["marks_awarded"] for g in grading_json.get("grading", [])
319
+ if g["question"].lower() == qid.lower()), [])
320
+
321
+ marks_text = ",".join(marks_list) if marks_list else "?"
322
+
323
+ # Compute candidate cell coordinates
324
+ # Convert cell_number -> (row, col)
325
+ row = (cell_number - 1) // cols
326
+ col = (cell_number - 1) % cols
327
+
328
+ # Preference: place in cell to the right (col + 1), if within grid and not occupied.
329
+ placed = False
330
+ candidates = []
331
+ # Right cell
332
+ if col + 1 < cols:
333
+ candidates.append((row, col + 1))
334
+ # same cell (fallback)
335
+ candidates.append((row, col))
336
+ # left cell
337
+ if col - 1 >= 0:
338
+ candidates.append((row, col - 1))
339
+
340
+ chosen = None
341
+ for (r_c, c_c) in candidates:
342
+ cell_id = r_c * cols + c_c + 1
343
+ if cell_id not in occupied:
344
+ chosen = (r_c, c_c)
345
+ occupied.add(cell_id)
346
+ break
347
+
348
+ if chosen is None:
349
+ # all occupied? just pick original cell
350
+ chosen = (row, col)
351
+
352
+ # Convert chosen cell to pixel coordinates (approx center-right)
353
+ r_c, c_c = chosen
354
+ x_c = int((c_c + 1) * cell_w_px - cell_w_px * 0.1) # near right edge of cell
355
+ y_c = int((r_c + 0.5) * cell_h_px)
356
+
357
+ # Print the imprint step to console
358
+ print(f"Page {p_index+1} | Question {qid} -> mapped cell {cell_number} -> chosen cell ({r_c},{c_c})"
359
+ f" -> pixel coords ({x_c},{y_c}) | marks: {marks_text}")
360
+
361
+ # Draw the text on the image (scale font according to cell size)
362
+ font_scale = max(0.6, min(1.6, cell_h_px / 60.0))
363
+ thickness = max(1, int(font_scale * 2))
364
+ # Use cv2.putText (BGR)
365
+ cv2.putText(img_cv, marks_text, (x_c, y_c), cv2.FONT_HERSHEY_SIMPLEX,
366
+ font_scale, (0, 0, 255), thickness, cv2.LINE_AA)
367
+
368
+ # Save annotated page
369
+ annotated_path = f"annotated_page_{p_index+1}.png"
370
+ cv2.imwrite(annotated_path, img_cv)
371
+ annotated_page_paths.append(annotated_path)
372
+ print(f"πŸ–Š Annotated page saved: {annotated_path}")
373
+
374
+ # Merge annotated pages into a PDF
375
  with open(output_pdf, "wb") as f:
376
+ f.write(img2pdf.convert(annotated_page_paths))
377
+
378
+ print(f"πŸ“‘ Imprinted PDF saved to: {output_pdf}")
379
+ # Compress output PDF only if > 20MB
380
+ compressed = compress_pdf(output_pdf)
381
+ if compressed != output_pdf:
382
+ print(f"πŸ“¦ Imprinted PDF compressed: {compressed}")
383
+ return compressed
384
+
385
+ # ---------- Main pipeline ----------
386
+ def align_and_grade_pipeline(qp_path, ms_path, ans_path, imprint=False):
387
+ """
388
+ Runs: compress (if needed) -> upload files -> alignment -> grading -> extract marks ->
389
+ optional imprint (per-page mapping + annotation).
390
+ Returns: (alignment_json_text, grading_markdown_text, grading_pdf_path, imprinted_pdf_path or None)
391
+ """
392
  try:
393
+ # Step 0: compress only if >20MB
394
+ qp_path = compress_pdf(qp_path)
395
+ ms_path = compress_pdf(ms_path)
396
+ ans_path = compress_pdf(ans_path)
397
 
398
+ # Upload files to Gemini
399
+ print("πŸ”Ό Uploading files to Gemini...")
400
+ qp_uploaded = genai.upload_file(path=qp_path, display_name="Question Paper")
401
+ ms_uploaded = genai.upload_file(path=ms_path, display_name="Markscheme")
402
+ ans_uploaded = genai.upload_file(path=ans_path, display_name="Answer Sheet")
403
 
404
  model = create_model()
405
 
406
+ # Step 1: ALIGN (JSON only)
407
+ print("1️⃣ Sending ALIGNMENT_PROMPT to Gemini (alignment step)...")
408
  resp = model.generate_content([
409
  PROMPTS["ALIGNMENT_PROMPT"]["content"],
410
  qp_uploaded,
411
  ms_uploaded,
412
  ans_uploaded
413
  ])
414
+
415
  json_output = getattr(resp, "text", None)
416
+ if not json_output and getattr(resp, "candidates", None):
417
  json_output = resp.candidates[0].content.parts[0].text
418
 
419
+ # Ensure we have text
420
+ if not json_output:
421
+ raise RuntimeError("No alignment JSON returned from Gemini.")
422
+
423
+ print("βœ… Alignment JSON received (truncated preview):")
424
+ print((json_output[:1000] + '...') if len(json_output) > 1000 else json_output)
425
+
426
+ # Step 2: GRADING (Markdown)
427
+ print("2️⃣ Sending GRADING_PROMPT to Gemini (grading step)...")
428
  response = model.generate_content([
429
  PROMPTS["GRADING_PROMPT"]["content"],
430
  json_output
431
  ])
432
+ grading_text = getattr(response, "text", None)
433
+ if not grading_text and getattr(response, "candidates", None):
434
+ grading_text = response.candidates[0].content.parts[0].text
435
 
436
+ if not grading_text:
437
+ raise RuntimeError("No grading output returned from Gemini.")
438
 
439
+ print("βœ… Grading Markdown received (truncated preview):")
440
+ print((grading_text[:1000] + '...') if len(grading_text) > 1000 else grading_text)
441
+
442
+ # Save grading PDF
443
+ base_name = os.path.splitext(os.path.basename(ans_path))[0]
444
+ grading_pdf_path = save_as_pdf(grading_text, f"{base_name}_graded.pdf")
445
+ print(f"πŸ“„ Grading PDF saved: {grading_pdf_path}")
446
+
447
+ # Step 2.5: Extract marks per question from grading text
448
+ grading_json = extract_marks_from_grading(grading_text)
449
+ print("πŸ”§ Extracted grading JSON (per-question marks):")
450
+ print(json.dumps(grading_json, indent=2))
451
+
452
+ imprinted_pdf_path = None
453
  if imprint:
454
+ print("✍ Imprint option enabled. Starting imprinting process...")
455
+ # Convert answer PDF to grid pages, ask Gemini for mapping per page and annotate
456
+ imprinted_pdf_path = f"{base_name}_imprinted.pdf"
457
+ imprinted_pdf_path = imprint_marks_using_mapping(ans_path, grading_json, imprinted_pdf_path, model)
458
+ print(f"βœ… Imprinting finished. Imprinted PDF at: {imprinted_pdf_path}")
459
 
460
+ return json_output, grading_text, grading_pdf_path, imprinted_pdf_path
461
 
462
  except Exception as e:
463
+ print("❌ Pipeline error:", e)
464
  return f"❌ Error: {e}", None, None, None
465
 
466
  # ---------- GRADIO APP ----------
467
  with gr.Blocks(title="LeadIB AI Grading (Alignment + Auto-Grading + Imprint)") as demo:
468
+ gr.Markdown("## πŸ“˜ LeadIB AI Grading\nUpload **Question Paper**, **Markscheme**, and **Student Answer Sheet**.\nSystem aligns β†’ grades β†’ optionally imprints marks (per-question, per-page mapping).")
469
 
470
  with gr.Row():
471
  qp_file = gr.File(label="πŸ“„ Upload Question Paper (PDF)")
 
476
  run_button = gr.Button("πŸš€ Run Alignment + Grading")
477
 
478
  with gr.Row():
479
+ json_output_box = gr.Textbox(label="πŸ“‘ Step 1: Alignment (JSON)", lines=20)
480
+ grading_output_box = gr.Textbox(label="πŸ“ Step 2: Grading (Markdown)", lines=20)
481
+
482
+ grading_pdf_file = gr.File(label="πŸ“₯ Download Grading PDF")
483
+ imprint_pdf_file = gr.File(label="πŸ“₯ Download Imprinted PDF (Optional)")
484
+
485
+ def run_pipeline(qp_file_obj, ms_file_obj, ans_file_obj, imprint_flag):
486
+ # Gradio File objects have .name attribute when saved locally
487
+ qp_path = qp_file_obj.name
488
+ ms_path = ms_file_obj.name
489
+ ans_path = ans_file_obj.name
490
+
491
+ alignment_text, grading_text, grading_pdf_path, imprinted_pdf_path = align_and_grade_pipeline(
492
+ qp_path, ms_path, ans_path, imprint=imprint_flag
493
+ )
494
 
495
+ # For Gradio file outputs: return file paths (or None)
496
+ return alignment_text, grading_text, grading_pdf_path, imprinted_pdf_path
497
 
498
  run_button.click(
499
+ fn=run_pipeline,
500
  inputs=[qp_file, ms_file, ans_file, imprint_toggle],
501
+ outputs=[json_output_box, grading_output_box, grading_pdf_file, imprint_pdf_file]
502
  )
503
 
504
  if __name__ == "__main__":