Spaces:
Paused

MathematicsApps / tutor_chat.py
jobinv's picture
Upload 25 files
4707b1a verified
Raw History Blame Contribute Delete
19.5 kB
"""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."