"""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"(? 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 - Green = a secure checkpoint - Amber = verify a sign, component or unit - Red = 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, }