Spaces:
Paused
Paused
Upload 24 files
Browse filesFiles changed (4)
- README.md+26-2
- START_HERE.txt+8
- app.py+87-1
- tutor_chat.pyAdded+305
47 unmodified lines48495051525355 unmodified lines10911011111211311411511611711811912026 unmodified lines14714814915015115215315447 unmodified linesmodel for each newly added question;- a reusable user question bank with JSON backup and restore-by-upload, extendingthe original mapping of 149 reference questions without rebuilding the app;- a classroom worksheet generator with teacher solutions in Markdown, editableWord, and print-ready PDF formats.55 unmodified lines- `OPENAI_API_KEY` โ API credential;- `VISION_MODEL` โ optional model override; defaults to `gpt-4.1-mini`.The learner must also tick **Use optional AI vision tutor** for a submission.When it is not ticked, the work image stays in the Space runtime and is handledby local OCR. If optional vision is enabled, the uploaded image is sent to theconfigured API for that review.### Creative Lab soundBrowsers permit sound after a learner gesture. Clicking the model or **Start26 unmodified lines```The tests exercise every procedural generator across difficulties and seeds,all eight editable visual scenes, question ingestion/deduplication, answermatching, gamification, Plotly figure creation and worksheet output.## Content and affiliation notice47 unmodified lines4849505152535455565758596055 unmodified lines11611711811912012112212312412512612712812913013113213313413513613713813914014114214326 unmodified lines17017117217317417517617717847 unmodified linesmodel for each newly added question;- a reusable user question bank with JSON backup and restore-by-upload, extendingthe original mapping of 149 reference questions without rebuilding the app;- a **Mechanics Tutor Chat** automatically grounded in the active generatedquestion, verified solution, expected answers, hints and theory;- six suggested clarification prompts plus free-form follow-up questions usingtyped text, microphone/uploaded audio, or an uploaded equation, diagram orhandwritten image;- a deterministic local tutor for core explanations and image/OCR checking,with an optional conversational AI tutor when `OPENAI_API_KEY` is configured;- a classroom worksheet generator with teacher solutions in Markdown, editableWord, and print-ready PDF formats.55 unmodified lines- `OPENAI_API_KEY` โ API credential;- `VISION_MODEL` โ optional model override; defaults to `gpt-4.1-mini`.- `TUTOR_MODEL` โ optional chatbot model override; defaults to `gpt-4.1-mini`.The learner must also tick **Use optional AI vision tutor** for a submission.When it is not ticked, the work image stays in the Space runtime and is handledby local OCR. If optional vision is enabled, the uploaded image is sent to theconfigured API for that review.### Mechanics Tutor ChatThe **๐ฌ Mechanics tutor chat** tab follows the current Mission Controlquestion. Generating a new mission resets and re-grounds the conversation.Students may select one of six suggested questions, type a follow-up, record avoice query, or upload an equation/diagram/working image. Voice is transcribedusing the same local-or-configured transcription route as Question Intake.By default, the verified local tutor can explain theory, equations,sign conventions, first hints, complete solutions, similar questions and OCR-detected answer checkpoints. With `OPENAI_API_KEY`, learners can explicitlycheck **Use configured AI tutor for this message** for open-ended responses andimage explanations grounded in the validated question data. Images are not sentto the configured API unless that checkbox is selected.### Creative Lab soundBrowsers permit sound after a learner gesture. Clicking the model or **Start26 unmodified lines```The tests exercise every procedural generator across difficulties and seeds,all eight editable visual scenes, question ingestion/deduplication, multimodaltutor grounding, answer matching, gamification, Plotly figure creation andworksheet output.## Content and affiliation notice
37 unmodified lines38394037 unmodified lines-------------------Open the "Question intake" tab to paste questions, upload images/PDF/Word/textfiles, or record a spoken question. Download the JSON bank as a portable backup.37 unmodified lines383940414243444546474837 unmodified lines-------------------Open the "Question intake" tab to paste questions, upload images/PDF/Word/textfiles, or record a spoken question. Download the JSON bank as a portable backup.MECHANICS TUTOR CHAT--------------------Generate a mission and open the "Mechanics tutor chat" tab. Students can usethe suggested prompts, type a question, record a voice query, or upload anequation/diagram/working image. The verified local tutor works without a key.For optional open-ended AI replies, configure OPENAI_API_KEY and let the learnerexplicitly enable the AI tutor checkbox for that message.
37 unmodified lines38394041424375 unmodified lines119120121122123124546 unmodified lines67167267367467567629 unmodified lines70670770870971071171242 unmodified lines75575675775875976037 unmodified linesquestion_visual_payload,)from theory import theory_forfrom worksheet_exports import export_worksheet_bundle75 unmodified lines0,str(q["seed"]),profile_html(profile),)546 unmodified linesintake_export_btn = gr.Button("Download question bank JSON", scale=1)intake_bank_file = gr.File(label="Question bank backup (.json)")with gr.Tab("๐ Theory vault"):theory_md = gr.Markdown(theory_for(INITIAL_QUESTION),29 unmodified linesgenerate_btn.click(create_mission,inputs=[topic, difficulty, seed, profile_state],outputs=[question_state, question_md, mission_visual, line_plot, model_plot, theory_md, hint_md, solution_md, hint_index_state, seed, profile_panel],)hint_btn.click(next_hint,42 unmodified linesoutputs=[intake_selected_question, intake_visual],)intake_export_btn.click(export_bank_file, outputs=[intake_bank_file])custom_inputs = [custom_scenario,custom_context,37 unmodified lines3839404142434445464748495075 unmodified lines126127128129130131132133546 unmodified lines68068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474529 unmodified lines77577677777877978078142 unmodified lines82482582682782882983083183283383483583683783883984084184284384484584637 unmodified linesquestion_visual_payload,)from theory import theory_forfrom tutor_chat import (DEFAULT_TUTOR_QUESTIONS,chat_with_tutor,clear_tutor_chat,tutor_context_markdown,tutor_welcome,)from worksheet_exports import export_worksheet_bundle75 unmodified lines0,str(q["seed"]),profile_html(profile),tutor_context_markdown(q),tutor_welcome(q),)546 unmodified linesintake_export_btn = gr.Button("Download question bank JSON", scale=1)intake_bank_file = gr.File(label="Question bank backup (.json)")with gr.Tab("๐ฌ Mechanics tutor chat"):gr.Markdown("""## Clarify the active question or its solutionThe tutor is grounded in the generated question, verified solution, expected answers, hints and theory. Ask in text, speak through the microphone, or upload an image of a diagram, equation or handwritten method.""")tutor_context = gr.Markdown(tutor_context_markdown(INITIAL_QUESTION),elem_classes=["glass-panel"],)tutor_chat = gr.Chatbot(value=tutor_welcome(INITIAL_QUESTION),label="Mechanics Tutor",height=520,latex_delimiters=LATEX_DELIMITERS,)gr.Markdown("### Suggested questions")tutor_prompt_buttons = []with gr.Row():for prompt in DEFAULT_TUTOR_QUESTIONS[:3]:tutor_prompt_buttons.append(gr.Button(prompt, size="sm"))with gr.Row():for prompt in DEFAULT_TUTOR_QUESTIONS[3:]:tutor_prompt_buttons.append(gr.Button(prompt, size="sm"))tutor_text = gr.Textbox(label="Ask a follow-up question",placeholder="Example: Why is acceleration negative in this solution?",lines=3,)tutor_use_ai = gr.Checkbox(label="Use configured AI tutor for this message",value=False,info="Requires OPENAI_API_KEY. Uploaded image and transcribed query are sent only when this is checked.",)with gr.Row(equal_height=False):tutor_audio = gr.Audio(label="Ask by voice",sources=["upload", "microphone"],type="filepath",)tutor_image = gr.Image(label="Upload an equation, diagram, or handwritten method",type="pil",image_mode="RGB",sources=["upload", "webcam", "clipboard"],height=260,)with gr.Row():tutor_send_btn = gr.Button("Send to mechanics tutor",variant="primary",elem_classes=["submit-btn"],)tutor_clear_btn = gr.Button("Clear conversation")tutor_input_status = gr.Markdown("Text works immediately. Voice is transcribed locally unless a configured speech service is available.",elem_classes=["privacy-note"],)with gr.Tab("๐ Theory vault"):theory_md = gr.Markdown(theory_for(INITIAL_QUESTION),29 unmodified linesgenerate_btn.click(create_mission,inputs=[topic, difficulty, seed, profile_state],outputs=[question_state, question_md, mission_visual, line_plot, model_plot, theory_md, hint_md, solution_md, hint_index_state, seed, profile_panel, tutor_context, tutor_chat],)hint_btn.click(next_hint,42 unmodified linesoutputs=[intake_selected_question, intake_visual],)intake_export_btn.click(export_bank_file, outputs=[intake_bank_file])tutor_send_btn.click(chat_with_tutor,inputs=[question_state, tutor_text, tutor_audio, tutor_image, tutor_use_ai, tutor_chat],outputs=[tutor_chat, tutor_text, tutor_audio, tutor_image, tutor_input_status],)tutor_text.submit(chat_with_tutor,inputs=[question_state, tutor_text, tutor_audio, tutor_image, tutor_use_ai, tutor_chat],outputs=[tutor_chat, tutor_text, tutor_audio, tutor_image, tutor_input_status],)tutor_clear_btn.click(clear_tutor_chat,inputs=[question_state],outputs=[tutor_chat, tutor_input_status],)for button, prompt in zip(tutor_prompt_buttons, DEFAULT_TUTOR_QUESTIONS):button.click(lambda selected=prompt: selected, outputs=[tutor_text])custom_inputs = [custom_scenario,custom_context,
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305"""Grounded multimodal mechanics tutor for generated questions and solutions."""
from __future__ import annotations
import base64from io import BytesIOimport osfrom pathlib import Pathfrom typing import Any
from PIL import Image
from engine import generate_questionfrom evaluator import extract_numbers, run_ocrfrom question_intake import transcribe_audiofrom 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.",)
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 _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 thestudent's level, identify signs and modelling assumptions, and use clearMarkdown and properly delimited LaTeX. Start with a hint unless the studentexplicitly asks for the full solution. If an image is supplied, describe onlylegible mathematical work and identify the first error. Never invent text froman 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
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(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", "why", "which law")): 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}" hints = question.get("hints", []) hint = hints[0] if hints else "Begin by drawing the physical model and labelling the known quantities." return ( f"This question tests **{question.get('topic_label', 'M1 mechanics')}**. " f"A productive next checkpoint is: {hint}\n\n" "Ask me about the concept, equation choice, sign convention, a particular solution step, or upload your working image." )
def chat_with_tutor( question: dict[str, Any] | None, message: str, audio_path: Any, image: Any, use_ai: bool, history: list[dict[str, Any]] | 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."
answer = _online_tutor(question, query, history, image, image_text) if use_ai else None if answer is None: answer = _offline_tutor(question, query, image_text, image is not None) if use_ai and os.getenv("OPENAI_API_KEY"): notes.append("The configured AI tutor was unavailable, so the verified local tutor answered.") elif use_ai: notes.append("The AI tutor is not configured, so the verified local tutor answered.") else: notes.append("Verified local tutor used. Configure OPENAI_API_KEY for open-ended conversational explanations.") 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."README.md+26-2
START_HERE.txt+8
app.py+87-1
tutor_chat.pyAdded+305