Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,16 +2,18 @@ import os
|
|
| 2 |
import re
|
| 3 |
import json
|
| 4 |
import subprocess
|
| 5 |
-
import
|
| 6 |
-
import
|
| 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 |
-
|
|
|
|
| 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 |
-
"""
|
|
|
|
|
|
|
|
|
|
| 104 |
if output_path is None:
|
| 105 |
base, ext = os.path.splitext(input_path)
|
| 106 |
output_path = f"{base}_compressed{ext}"
|
| 107 |
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
|
|
|
|
|
|
| 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 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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":
|
| 151 |
})
|
| 152 |
|
| 153 |
return grading_json
|
| 154 |
|
| 155 |
-
# ----------
|
| 156 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 157 |
pages = convert_from_path(pdf_path, dpi=200)
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
with open(output_pdf, "wb") as f:
|
| 179 |
-
f.write(img2pdf.convert(
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
try:
|
| 186 |
-
#
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
|
|
|
|
|
|
| 194 |
|
| 195 |
model = create_model()
|
| 196 |
|
| 197 |
-
#
|
|
|
|
| 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
|
| 206 |
json_output = resp.candidates[0].content.parts[0].text
|
| 207 |
|
| 208 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
response = model.generate_content([
|
| 210 |
PROMPTS["GRADING_PROMPT"]["content"],
|
| 211 |
json_output
|
| 212 |
])
|
| 213 |
-
|
| 214 |
-
if not
|
| 215 |
-
|
| 216 |
|
| 217 |
-
|
| 218 |
-
|
| 219 |
|
| 220 |
-
|
| 221 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 222 |
if imprint:
|
| 223 |
-
|
| 224 |
-
|
|
|
|
|
|
|
|
|
|
| 225 |
|
| 226 |
-
return json_output,
|
| 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 |
-
|
| 245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 246 |
|
| 247 |
-
|
| 248 |
-
|
| 249 |
|
| 250 |
run_button.click(
|
| 251 |
-
fn=
|
| 252 |
inputs=[qp_file, ms_file, ans_file, imprint_toggle],
|
| 253 |
-
outputs=[
|
| 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__":
|