import gradio as gr from transformers import pipeline import sympy as sp import json import os # ---------------------------- # Load AI model (reasoning) # ---------------------------- reasoner = pipeline("text2text-generation", model="google/flan-t5-small", device=-1) # ---------------------------- # Points storage (JSON file) # ---------------------------- POINTS_FILE = "points.json" def load_points(): if os.path.exists(POINTS_FILE): with open(POINTS_FILE, "r") as f: return json.load(f) return {"points": 0} def save_points(data): with open(POINTS_FILE, "w") as f: json.dump(data, f) # ---------------------------- # Core function: check kid’s answer + hints # ---------------------------- def check_answer(problem, kid_answer): data = load_points() try: # Sympy parses the math problem expr = sp.sympify(problem) correct_answer = sp.simplify(expr) # Try parsing kid’s answer try: kid_val = sp.simplify(kid_answer) except: kid_val = kid_answer # Hints: break problem into simpler parts hints = [] try: if isinstance(expr, sp.Basic): hints.append(f"🔹 First, look at the expression: {problem}") if expr.is_Add or expr.is_Mul: for arg in expr.args: hints.append(f"🔹 Consider part: {arg}") if expr.is_Pow: hints.append("🔹 Remember powers are solved before multiplication/addition.") if expr.is_Mul: hints.append("🔹 Multiplication/division happens before addition/subtraction.") if expr.is_Add: hints.append("🔹 After simplification, add/subtract the remaining parts.") except Exception: hints.append("🔹 Try simplifying step by step.") # Generate friendly reasoning with AI prompt = f"Explain to a 10-year-old how to solve {problem} step by step in simple language." reasoning = reasoner(prompt, max_length=180, temperature=0.5)[0]['generated_text'] # Compare answers if str(kid_val) == str(correct_answer): data["points"] += 10 save_points(data) feedback = ( f"🎉 Great job! Your answer {kid_answer} is correct.\n\n" + "\n".join(hints) + f"\n\n💡 Reasoning:\n{reasoning}\n\n✅ Final Answer: {correct_answer}" ) else: feedback = ( f"❌ Your answer {kid_answer} is not correct.\n\n" f"✅ Correct Answer: {correct_answer}\n\n" + "\n".join(hints) + f"\n\n💡 Reasoning:\n{reasoning}" ) return feedback, f"⭐ Your Points: {data['points']}" except Exception as e: return (f"⚠️ Could not process problem.\nError: {str(e)}", f"⭐ Your Points: {data['points']}") # ---------------------------- # Build Gradio Interface # ---------------------------- with gr.Blocks() as demo: gr.HTML( """