Spaces:
Paused
Paused
File size: 19,488 Bytes
7c6459b d6d612b 7c6459b 4707b1a 7c6459b 4707b1a 7c6459b d6d612b 7c6459b d6d612b 7c6459b d6d612b 7c6459b d6d612b 7c6459b 4707b1a 7c6459b 4707b1a 7c6459b 4707b1a 7c6459b 4707b1a 7c6459b 4707b1a 7c6459b 4707b1a 7c6459b | 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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 | """Grounded multimodal mechanics tutor for generated questions and solutions."""
from __future__ import annotations
import base64
from io import BytesIO
import os
from pathlib import Path
import re
from typing import Any
from PIL import Image
from engine import generate_question
from evaluator import extract_numbers, run_ocr
from question_intake import transcribe_audio
from theory import theory_for
DEFAULT_TUTOR_QUESTIONS = (
"Explain the concept behind this question in simple words.",
"Which equation should I use first, and why?",
"Explain the sign convention and directions in this question.",
"Give me only the first hint without revealing the final answer.",
"Check the method shown in my uploaded image.",
"Give me a similar example to try without showing its answer.",
)
QWEN_ENGINE = "Open-source Qwen (Hugging Face)"
LOCAL_ENGINE = "Verified local tutor"
OPENAI_ENGINE = "OpenAI tutor (optional)"
TUTOR_ENGINES = (QWEN_ENGINE, LOCAL_ENGINE, OPENAI_ENGINE)
OPEN_SOURCE_TUTOR_MODELS = (
"Qwen/Qwen3-4B-Instruct-2507",
"Qwen/Qwen3-30B-A3B-Instruct-2507",
"Qwen/Qwen2.5-7B-Instruct",
)
DEFAULT_OPEN_SOURCE_MODEL = os.getenv("HF_TUTOR_MODEL", OPEN_SOURCE_TUTOR_MODELS[0])
def tutor_context_markdown(question: dict[str, Any] | None) -> str:
if not question:
return "### No active mission\n\nGenerate a mission before opening the tutor."
return (
f"### Discussing: {question.get('title', 'Mechanics mission')}\n\n"
f"**{question.get('topic_label', 'M1 mechanics')}** · "
f"{question.get('difficulty', 'Exam standard')} · "
f"Question ID `{question.get('id', 'M1')}`"
)
def tutor_welcome(question: dict[str, Any] | None) -> list[dict[str, str]]:
if not question:
text = "Generate a mechanics mission, then ask me to explain its concept, equation, diagram, or solution."
else:
text = (
f"I’m ready to help with **{question.get('title', 'this mechanics question')}**. "
"Choose a suggested question below, type your own query, speak it, or upload an image of the part you want clarified."
)
return [{"role": "assistant", "content": text}]
def _as_image(image: Any) -> Image.Image | None:
if image is None:
return None
if isinstance(image, Image.Image):
return image.convert("RGB")
if isinstance(image, (str, Path)) and Path(image).is_file():
return Image.open(image).convert("RGB")
try:
return Image.fromarray(image).convert("RGB")
except Exception:
return None
def _image_data_url(image: Any) -> str | None:
pil = _as_image(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 _ground_truth(question: dict[str, Any]) -> str:
answers = ", ".join(
f"{answer.get('label')} = {answer.get('display')}"
for answer in question.get("expected_answers", [])
)
steps = "\n".join(
f"{index}. {step}" for index, step in enumerate(question.get("solution_steps", []), 1)
)
hints = "\n".join(f"- {hint}" for hint in question.get("hints", []))
return f"""QUESTION
{question.get('prompt', '')}
VERIFIED SOLUTION PATH
{steps}
VERIFIED ANSWERS
{answers}
AVAILABLE HINTS
{hints}
THEORY
{theory_for(question)}
"""
def _recent_text_history(history: list[dict[str, Any]], limit: int = 8) -> list[dict[str, str]]:
recent: list[dict[str, str]] = []
for message in history[-limit:]:
role = str(message.get("role", "user"))
content = message.get("content", "")
if isinstance(content, str) and content.strip():
recent.append({"role": role, "content": content[:1600]})
return recent
def _open_source_tutor(
question: dict[str, Any],
query: str,
history: list[dict[str, Any]],
extracted_image_text: str,
model: str,
) -> tuple[str | None, str]:
"""Call a routed open-source chat model through Hugging Face."""
token = (
os.getenv("HF_TOKEN")
or os.getenv("HUGGING_FACE_HUB_TOKEN")
or os.getenv("HUGGINGFACEHUB_API_TOKEN")
)
if not token:
return None, "HF_TOKEN is not configured; the verified local tutor answered instead."
selected_model = str(model or DEFAULT_OPEN_SOURCE_MODEL).strip()
if "/" not in selected_model or len(selected_model) > 160:
selected_model = DEFAULT_OPEN_SOURCE_MODEL
try:
from huggingface_hub import InferenceClient
system_prompt = f"""You are a patient Pearson Edexcel International Advanced Level M1 mechanics tutor.
Answer the student's exact question about the active problem. The VERIFIED
PROBLEM DATA below is authoritative: never change its numerical values, never
invent a result, and never contradict its solution. Explain the physical idea,
sign convention, modelling assumption and equation choice in clear teaching
language. Use Markdown and properly delimited LaTeX. Give only a hint unless
the student explicitly asks for the final answer or full solution. If OCR text
is supplied, discuss only legible content. Keep the answer focused and under
400 words.
VERIFIED PROBLEM DATA
{_ground_truth(question)}
OCR FROM THE CURRENT IMAGE
{extracted_image_text or '(no image supplied)'}
"""
messages = [{"role": "system", "content": system_prompt}]
messages.extend(_recent_text_history(history))
messages.append({"role": "user", "content": query})
client = InferenceClient(
provider=os.getenv("HF_INFERENCE_PROVIDER", "auto"),
api_key=token,
timeout=float(os.getenv("HF_TUTOR_TIMEOUT", "50")),
)
response = client.chat_completion(
model=selected_model,
messages=messages,
max_tokens=800,
temperature=0.25,
top_p=0.9,
)
content = getattr(response.choices[0].message, "content", "")
if isinstance(content, list):
content = "\n".join(
str(item.get("text", "")) if isinstance(item, dict) else str(item)
for item in content
)
answer = re.sub(r"<think>[\s\S]*?</think>", "", str(content)).strip()
if answer:
return answer, f"Open-source tutor used: {selected_model}."
return None, "The selected open-source model returned no answer; the local tutor responded."
except Exception:
return None, "The Hugging Face open-source model was unavailable; the verified local tutor answered instead."
def _online_tutor(
question: dict[str, Any],
query: str,
history: list[dict[str, Any]],
image: Any,
extracted_image_text: str,
) -> str | None:
if not os.getenv("OPENAI_API_KEY"):
return None
try:
from openai import OpenAI
recent = []
for message in history[-8:]:
role = message.get("role", "user")
content = message.get("content", "")
if isinstance(content, str):
recent.append(f"{role.upper()}: {content[:1200]}")
prompt = f"""You are a patient Pearson Edexcel International A Level M1 mechanics tutor.
Use only the verified question data below for numerical claims. Explain at the
student's level, identify signs and modelling assumptions, and use clear
Markdown and properly delimited LaTeX. Start with a hint unless the student
explicitly asks for the full solution. If an image is supplied, describe only
legible mathematical work and identify the first error. Never invent text from
an unclear image. Keep the reply focused and under 350 words.
{_ground_truth(question)}
RECENT CONVERSATION
{chr(10).join(recent)}
OCR FROM CURRENT IMAGE
{extracted_image_text or '(no image text)'}
STUDENT QUERY
{query}
"""
content: list[dict[str, str]] = [{"type": "input_text", "text": prompt}]
data_url = _image_data_url(image)
if data_url:
content.append({"type": "input_image", "image_url": data_url})
response = OpenAI().responses.create(
model=os.getenv("TUTOR_MODEL", "gpt-4.1-mini"),
input=[{"role": "user", "content": content}],
max_output_tokens=800,
)
answer = response.output_text.strip()
return answer or None
except Exception:
return None
def _matching_step(question: dict[str, Any], keywords: tuple[str, ...]) -> str | None:
for step in question.get("solution_steps", []):
if any(keyword in step.lower() for keyword in keywords):
return step
return None
_QUERY_STOP_WORDS = {
"about", "after", "also", "answer", "because", "could", "does", "explain",
"from", "have", "into", "problem", "question", "should", "that", "their",
"then", "there", "these", "this", "what", "when", "where", "which", "why",
"with", "would", "your",
}
def _relevant_solution_steps(question: dict[str, Any], query: str, limit: int = 2) -> list[str]:
"""Return verified steps whose language most closely matches the query."""
query_terms = {
term for term in re.findall(r"[a-z][a-z0-9_-]{2,}", query.lower())
if term not in _QUERY_STOP_WORDS
}
scored: list[tuple[int, int, str]] = []
for index, step in enumerate(question.get("solution_steps", [])):
step_terms = set(re.findall(r"[a-z][a-z0-9_-]{2,}", str(step).lower()))
scored.append((len(query_terms & step_terms), -index, str(step)))
scored.sort(reverse=True)
matched = [step for score, _, step in scored if score > 0][:limit]
if matched:
return matched
return [str(step) for step in question.get("solution_steps", [])[:limit]]
def _known_values_markdown(question: dict[str, Any]) -> str:
values = []
for key, value in question.get("diagram_data", {}).items():
if isinstance(value, (int, float, str, bool)) and len(str(value)) <= 40:
label = str(key).replace("_", " ").strip().title()
values.append(f"- **{label}:** {value}")
return "\n".join(values[:12]) or "Read the labelled quantities directly from the active question and diagram."
def _image_feedback(question: dict[str, Any], text: str) -> str:
if not text:
return (
"I received the image, but the local reader could not extract reliable mathematics. "
"Retake it square-on with bright, even lighting, or type the expression you want checked."
)
detected = extract_numbers(text)
expected = question.get("expected_answers", [])
matches: list[str] = []
for answer in expected:
target = float(answer.get("value", 0))
tolerance = float(answer.get("tolerance", max(0.02, abs(target) * 0.01)))
nearest = min(detected, key=lambda value: abs(value - target)) if detected else None
if nearest is not None and abs(nearest - target) <= tolerance:
matches.append(f"- ✅ {answer.get('label')}: detected {nearest:g}, consistent with the verified answer.")
elif nearest is not None:
matches.append(f"- 🔶 {answer.get('label')}: nearest detected value {nearest:g}; recheck the method before this result.")
report = "\n".join(matches) if matches else "No final answer could be matched confidently."
first_step = question.get("solution_steps", ["Rebuild the physical model first."])[0]
safe_text = text[:900].replace("```", "'''")
return f"""I read the following from the uploaded image:
```text
{safe_text}
```
{report}
Start checking from this verified checkpoint: {first_step}
"""
def _offline_tutor(
question: dict[str, Any],
query: str,
image_text: str,
has_image: bool,
) -> str:
lower = query.lower()
if has_image or any(word in lower for word in ("image", "photo", "working", "method", "mistake")):
if image_text or has_image:
return _image_feedback(question, image_text)
if any(word in lower for word in ("theory", "concept", "simple words", "understand")):
return theory_for(question)
if any(phrase in lower for phrase in ("given values", "known values", "what is given", "data in the question")):
return f"### Known information in this problem\n\n{_known_values_markdown(question)}"
if any(phrase in lower for phrase in ("what is asked", "what to find", "required answer", "find in this")):
targets = "\n".join(
f"- {answer.get('label', 'Required quantity')}"
for answer in question.get("expected_answers", [])
) or "- Follow the command words in the final sentence of the active question."
return f"### What the problem asks you to find\n\n{targets}\n\nI have not revealed the numerical answers."
if any(word in lower for word in ("first hint", "only hint", "start", "first step")):
hints = question.get("hints", [])
hint = hints[0] if hints else question.get("solution_steps", ["Draw and label the physical model."])[0]
return f"### First hint\n\n{hint}\n\nTry that step and tell me what equation you obtain."
if any(word in lower for word in ("sign", "direction", "positive", "negative")):
step = _matching_step(question, ("positive", "sign", "direction"))
if step:
return f"### Sign convention\n\n{step}\n\nEvery velocity, acceleration, force or displacement must then keep that declared sign."
return (
"### Sign convention\n\nChoose and state a positive direction before substituting. "
"Quantities pointing with it are positive; quantities pointing against it are negative. "
"The diagram arrows should agree with every algebraic sign."
)
if any(word in lower for word in ("equation", "formula", "which law")) or "why this equation" in lower:
steps = question.get("solution_steps", [])[:3]
body = "\n".join(f"{index}. {step}" for index, step in enumerate(steps, 1))
return f"### Equation choice\n\n{body}\n\nThe first equation is chosen because it contains the known quantities and the required unknown while respecting the physical model."
if any(word in lower for word in ("similar", "another example", "practice")):
seed = int(question.get("seed", 1)) + 104_729
similar = generate_question(
question.get("topic_label", "Mixed mission"),
question.get("difficulty", "Exam standard"),
seed,
)
return f"""### Similar practice question
{similar.get('prompt', '').strip()}
I have deliberately hidden the answer. Send me your first equation when you are ready.
"""
if any(word in lower for word in ("answer", "solution", "solve", "full method")):
steps = "\n".join(
f"{index}. {step}" for index, step in enumerate(question.get("solution_steps", []), 1)
)
answers = "\n".join(
f"- **{answer.get('label')}:** {answer.get('display')}"
for answer in question.get("expected_answers", [])
)
return f"### Verified solution\n\n{steps}\n\n### Final answers\n\n{answers}"
relevant_steps = _relevant_solution_steps(question, query)
if relevant_steps:
body = "\n".join(f"{index}. {step}" for index, step in enumerate(relevant_steps, 1))
return (
f"### Answer about the active problem\n\n"
f"This is a **{question.get('topic_label', 'M1 mechanics')}** problem. "
"The verified solution points most relevant to your question are:\n\n"
f"{body}\n\n"
"Tell me which line or quantity is unclear and I will narrow the explanation further."
)
hint = question.get("hints", ["Draw and label the physical model first."])[0]
return f"### Active-problem guidance\n\n{hint}"
def chat_with_tutor(
question: dict[str, Any] | None,
message: str,
audio_path: Any,
image: Any,
tutor_engine: str | bool,
history: list[dict[str, Any]] | None,
open_source_model: str | None = None,
) -> tuple[list[dict[str, Any]], str, None, None, str]:
history = list(history or tutor_welcome(question))
if not question:
history.append({"role": "user", "content": message or "Help me with the question."})
history.append({"role": "assistant", "content": "Generate a mission first so I can use its verified question and solution."})
return history, "", None, None, "No active mission."
notes: list[str] = []
voice_text = ""
if audio_path:
path = Path(str(audio_path))
if path.is_file():
voice_text, voice_note = transcribe_audio(path)
notes.append(voice_note)
image_text = ""
if image is not None:
image_text, image_note = run_ocr(image)
notes.append(image_note)
query_parts = [part.strip() for part in (message or "", voice_text) if part and part.strip()]
if not query_parts and image is not None:
query_parts.append("Please check and explain the work in my uploaded image.")
if not query_parts:
return history, message or "", None, image, "Type, speak, or upload a question before sending."
query = "\n".join(query_parts)
display_query = query
if voice_text:
display_query = "🎙️ " + query
if image is not None:
display_query += "\n\n📷 Image attached for explanation."
# Boolean values are retained for backward compatibility with earlier app
# versions: True meant OpenAI and False meant the local deterministic tutor.
if tutor_engine is True:
selected_engine = OPENAI_ENGINE
elif tutor_engine is False or tutor_engine not in TUTOR_ENGINES:
selected_engine = LOCAL_ENGINE
else:
selected_engine = str(tutor_engine)
answer = None
engine_note = ""
if selected_engine == QWEN_ENGINE:
answer, engine_note = _open_source_tutor(
question,
query,
history,
image_text,
open_source_model or DEFAULT_OPEN_SOURCE_MODEL,
)
elif selected_engine == OPENAI_ENGINE:
answer = _online_tutor(question, query, history, image, image_text)
if answer is not None:
engine_note = f"OpenAI tutor used: {os.getenv('TUTOR_MODEL', 'gpt-4.1-mini')}."
if answer is None:
answer = _offline_tutor(question, query, image_text, image is not None)
if engine_note:
notes.append(engine_note)
elif selected_engine == OPENAI_ENGINE and os.getenv("OPENAI_API_KEY"):
notes.append("The configured AI tutor was unavailable, so the verified local tutor answered.")
elif selected_engine == OPENAI_ENGINE:
notes.append("The AI tutor is not configured, so the verified local tutor answered.")
else:
notes.append("Verified local tutor used.")
elif engine_note:
notes.append(engine_note)
history.append({"role": "user", "content": display_query})
history.append({"role": "assistant", "content": answer})
status = "\n\n".join(note for note in notes if note) or "Text question processed."
return history, "", None, None, status
def clear_tutor_chat(question: dict[str, Any] | None) -> tuple[list[dict[str, str]], str]:
return tutor_welcome(question), "Conversation cleared; the active mission remains linked."
|