Spaces:
Paused
Paused
File size: 10,822 Bytes
f78142c | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 | """Handwritten-work intake, deterministic marking and optional vision review."""
from __future__ import annotations
import base64
from io import BytesIO
import os
import re
from typing import Any
from PIL import Image, ImageFilter, ImageOps
from gamification import apply_result
NUMBER_RE = re.compile(r"(?<![A-Za-z])[-+]?\d+(?:\.\d+)?(?:[eE][-+]?\d+)?")
FRACTION_RE = re.compile(r"(?<![\d.])([-+]?\d+(?:\.\d+)?)\s*/\s*(\d+(?:\.\d+)?)")
def _as_pil(image: Any) -> Image.Image | None:
if image is None:
return None
if isinstance(image, Image.Image):
return image.convert("RGB")
if isinstance(image, str) and os.path.exists(image):
return Image.open(image).convert("RGB")
try:
return Image.fromarray(image).convert("RGB")
except Exception:
return None
def preprocess_for_ocr(image: Any) -> Image.Image | None:
pil = _as_pil(image)
if pil is None:
return None
gray = ImageOps.grayscale(pil)
gray = ImageOps.autocontrast(gray, cutoff=1)
if max(gray.size) < 1800:
gray = gray.resize((gray.width * 2, gray.height * 2), Image.Resampling.LANCZOS)
gray = gray.filter(ImageFilter.SHARPEN)
# A moderate threshold helps ink stand out without erasing pencil strokes.
return gray.point(lambda p: 255 if p > 205 else 0)
def run_ocr(image: Any) -> tuple[str, str]:
processed = preprocess_for_ocr(image)
if processed is None:
return "", "No image was uploaded."
try:
import pytesseract
text = pytesseract.image_to_string(processed, config="--psm 6")
cleaned = "\n".join(line.rstrip() for line in text.splitlines() if line.strip())
if not cleaned:
return "", "The image was received, but no readable text was detected. Use bright, even lighting and a straight camera angle."
return cleaned, "OCR completed. Handwritten mathematics may need confirmation in the final-answer box."
except Exception as exc:
return "", f"OCR is unavailable in this runtime ({type(exc).__name__}). Enter the final answer manually for deterministic marking."
def extract_numbers(text: str) -> list[float]:
if not text:
return []
normalised = (
text.replace("−", "-").replace("–", "-").replace("×", "x")
.replace(",", "").replace("°", "")
)
values: list[float] = []
def fraction_value(match: re.Match) -> str:
numerator, denominator = float(match.group(1)), float(match.group(2))
if denominator:
token = 9_876_543 + len(values)
values.append(numerator / denominator)
return f" Z{token}Z "
return match.group(0)
without_fractions = FRACTION_RE.sub(fraction_value, normalised)
for match in NUMBER_RE.finditer(without_fractions):
raw = match.group(0)
# Ignore the artificial placeholders used for fractions.
if raw.startswith("987654"):
continue
try:
values.append(float(raw))
except ValueError:
pass
return values
def _match_answers(expected: list[dict], candidates: list[float]) -> tuple[list[dict], float]:
remaining = list(enumerate(candidates))
outcomes = []
for answer in expected:
target = float(answer["value"])
tolerance = float(answer.get("tolerance", max(0.02, abs(target) * 0.01)))
if remaining:
idx, candidate = min(remaining, key=lambda pair: abs(pair[1] - target))
error = abs(candidate - target)
matched = error <= tolerance
if matched:
remaining = [pair for pair in remaining if pair[0] != idx]
else:
candidate, error, matched = None, None, False
outcomes.append({
"answer": answer,
"candidate": candidate,
"error": error,
"matched": matched,
})
ratio = sum(1 for item in outcomes if item["matched"]) / max(1, len(outcomes))
return outcomes, ratio
def _diagnose_common_error(question: dict, candidates: list[float]) -> dict | None:
for error in question.get("common_errors", []):
try:
target = float(error["value"])
except (KeyError, TypeError, ValueError):
continue
tolerance = max(0.04, abs(target) * 0.012)
if any(abs(value - target) <= tolerance for value in candidates):
return error
return None
def _image_data_url(image: Any) -> str | None:
pil = _as_pil(image)
if pil is None:
return None
pil.thumbnail((1800, 1800))
buffer = BytesIO()
pil.save(buffer, format="JPEG", quality=88, optimize=True)
return "data:image/jpeg;base64," + base64.b64encode(buffer.getvalue()).decode("ascii")
def optional_vision_review(question: dict, image: Any) -> str:
"""Use a configured OpenAI vision model; fail closed to local feedback."""
if not os.getenv("OPENAI_API_KEY"):
return "Optional AI vision is not configured. Local OCR and exact-answer marking were used."
data_url = _image_data_url(image)
if not data_url:
return "Upload a working image to use optional AI vision review."
try:
from openai import OpenAI
expected = ", ".join(f"{a['label']}={a['display']}" for a in question["expected_answers"])
solution = "\n".join(f"{i+1}. {s}" for i, s in enumerate(question["solution_steps"]))
prompt = f"""You are a careful Pearson Edexcel IAL M1 mechanics tutor.
Read the student's handwritten working in the image. Compare it only with the
ground-truth question and solution below. Do not invent unreadable content.
Identify the first mathematical or modelling error, quote the student's
relevant expression if legible, explain why it is wrong, and give one short
correction prompt. Use supportive Markdown in no more than 180 words.
QUESTION:
{question['prompt']}
EXPECTED FINAL ANSWERS: {expected}
GROUND-TRUTH METHOD:
{solution}
"""
client = OpenAI()
response = client.responses.create(
model=os.getenv("VISION_MODEL", "gpt-4.1-mini"),
input=[{
"role": "user",
"content": [
{"type": "input_text", "text": prompt},
{"type": "input_image", "image_url": data_url},
],
}],
max_output_tokens=450,
)
return response.output_text.strip()
except Exception as exc:
return f"Optional AI vision could not run ({type(exc).__name__}). Local deterministic feedback remains available."
def evaluate_submission(
question: dict,
image: Any,
final_answer: str,
profile: dict | None,
use_ai_vision: bool = False,
) -> dict[str, Any]:
if not question:
return {
"feedback": "Generate a mission before submitting work.",
"ocr": "",
"profile": profile or {},
"correct": False,
"score_ratio": 0.0,
"xp_note": "",
}
ocr_text, ocr_status = run_ocr(image) if image is not None else ("", "No image uploaded; the typed answer was checked.")
typed_numbers = extract_numbers(final_answer or "")
ocr_numbers = extract_numbers(ocr_text)
# Typed values are authoritative because handwriting OCR can confuse signs,
# fractions and powers. OCR remains the fallback when no typed value exists.
candidates = typed_numbers if typed_numbers else ocr_numbers
outcomes, ratio = _match_answers(question.get("expected_answers", []), candidates)
correct = bool(outcomes) and all(item["matched"] for item in outcomes)
profile, xp_note = apply_result(profile, question, correct, ratio)
scored_marks = round(question.get("marks", 0) * ratio)
rows = []
for item in outcomes:
answer = item["answer"]
if item["matched"]:
rows.append(f"- ✅ **{answer['label']}**: matched {item['candidate']:.5g}")
elif item["candidate"] is None:
rows.append(f"- ⚪ **{answer['label']}**: no readable value found; target is {answer['display']}")
else:
rows.append(f"- 🔶 **{answer['label']}**: detected {item['candidate']:.5g}; target is {answer['display']}")
result_rows = "\n".join(rows)
diagnosis = _diagnose_common_error(question, candidates)
if correct:
headline = "## 🌟 Mission cleared"
coaching = (
"Your final values are consistent with the validated solution. "
"Now compare your written method with the mark-scheme path below so you also secure the method marks."
)
elif not candidates:
headline = "## 📸 I need one clearer mathematical signal"
coaching = (
"The work image was received, but I could not reliably isolate a final numerical answer. "
"Retake the photo square-on in bright light or type the final value(s) in the box, separated by commas."
)
elif diagnosis:
headline = f"## 🧠First correction: {diagnosis['title']}"
coaching = diagnosis["explanation"]
else:
missing = next((item for item in outcomes if not item["matched"]), None)
key_step = question.get("solution_steps", ["Rebuild the model and equation."])[min(1, len(question.get("solution_steps", [])) - 1)]
label = missing["answer"]["label"] if missing else "the final value"
headline = f"## 🔧 Rebuild {label}"
coaching = f"Your numerical result is not yet consistent with the model. Return to this checkpoint: {key_step}"
checkpoints = "\n".join(
f"{i+1}. {step}" for i, step in enumerate(question.get("solution_steps", [])[:5])
)
ai_section = ""
if use_ai_vision:
ai_section = "\n\n### Optional visual tutor review\n\n" + optional_vision_review(question, image)
feedback = f"""
{headline}
**Estimated evidence score:** {scored_marks}/{question.get('marks', 0)} marks · **{xp_note}**
{coaching}
### Answer checkpoints
{result_rows}
### Colour replay guide
- <span style="color:#22c55e"><b>Green</b></span> = a secure checkpoint
- <span style="color:#f59e0b"><b>Amber</b></span> = verify a sign, component or unit
- <span style="color:#ef4444"><b>Red</b></span> = rebuild from the physical model
### Correct method path
{checkpoints}
{ai_section}
"""
safe_ocr = ocr_text[:1800].replace("```", "'''") if ocr_text else "(no OCR text)"
ocr_report = f"""
### Image reading
{ocr_status}
```text
{safe_ocr}
```
Detected numeric values: `{', '.join(f'{v:g}' for v in ocr_numbers) if ocr_numbers else 'none'}`
"""
return {
"feedback": feedback,
"ocr": ocr_report,
"profile": profile,
"correct": correct,
"score_ratio": ratio,
"xp_note": xp_note,
}
|