import os import openai import gradio as gr import pytesseract from PIL import Image import random openai.api_key = os.getenv("OPENAI_API_KEY") # -- OCR + Auto-fill -- def extract_and_fill(img): try: text = pytesseract.image_to_string(img) return text, text except Exception as e: return f"โŒ Error: {e}", "" # -- Solver -- def solve_question(q, mode): if not q: return "โš ๏ธ Please enter a question.", "" prompt = { "๐Ÿ’ก Hint": f"Give a helpful hint. Question: {q}", "๐Ÿ”„ Steps": f"Explain step-by-step. Question: {q}", "โœ… Final": f"Explain and give the final answer. Question: {q}" }.get(mode, q) try: res = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}] ) full = res.choices[0].message.content.strip() final = full.split("Final Answer:")[-1].strip() if "Final Answer:" in full else "" return full, final except Exception as e: return f"โŒ Error: {str(e)}", "" # -- Game Mode -- def generate_game_question(grade): prompt = f"Create a {grade} math question with 1 correct and 3 incorrect answers. Format: Question: ... A: ... B: ... C: ... D: ... Correct: ..." try: res = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompt}] ) text = res.choices[0].message.content.strip() lines = text.splitlines() question = [l for l in lines if l.startswith("Question:")][0][9:].strip() choices = {l.split(":")[0]: l.split(":")[1].strip() for l in lines if l[:1] in "ABCD"} correct = [l for l in lines if l.startswith("Correct:")][0].split(":")[1].strip() correct_full = f"{correct}: {choices[correct]}" shuffled = [f"{k}: {v}" for k, v in random.sample(list(choices.items()), len(choices))] return question, gr.update(choices=shuffled), correct_full except Exception as e: return "โŒ Error generating question.", gr.update(choices=[]), "" def check_answer(selected, correct): if not selected: return "โ“ Choose an answer." return "โœ… Correct!" if selected == correct else "โŒ Try again." # -- Smart Tutor -- def smart_tutor(q, attempt, mode, concept, grade): if not q: return "โš ๏ธ Please enter a question." prompts = { "๐Ÿ’ก Just a Hint": f"Give a hint for this {grade} level question: {q}", "โœ… Check My Work": f"My attempt: {attempt}. Question: {q}. Feedback?", "๐Ÿงญ Walk Me Through It": f"Guide me through this {grade} level question: {q}", "๐Ÿ” Try a Similar Problem": f"Create a similar problem to: {q}", "๐Ÿ“˜ Explain the Concept": f"Explain the concept of '{concept}' for {grade} level." } try: res = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompts[mode]}] ) return res.choices[0].message.content.strip() except Exception as e: return f"โŒ Error: {str(e)}" # -- AI Lab -- def ai_lab(text, mode): if not text: return "โš ๏ธ Enter content" prompts = { "๐Ÿ” Predict Difficulty": f"How hard is this? {text}", "๐Ÿง  Classify Topic": f"What topic is this? {text}", "๐Ÿงช Create Practice Set": f"Make 3 problems for: {text}", "๐Ÿง  Explain Confusion Point": f"Why is this confusing: {text}", "๐ŸŽฏ Make Similar Questions": f"Make 2 similar questions: {text}", "๐ŸŽ“ Estimate Grade Level": f"What grade is this? {text}", "๐Ÿ”ข Predict Step Count": f"How many steps to solve this? {text}", "๐Ÿงฉ Extract Keywords": f"List math keywords in: {text}", "๐Ÿšซ Common Mistakes": f"What mistakes are made with: {text}" } try: res = openai.ChatCompletion.create( model="gpt-3.5-turbo", messages=[{"role": "user", "content": prompts[mode]}] ) return res.choices[0].message.content.strip() except Exception as e: return f"โŒ Error: {str(e)}" # -- Settings -- settings = {"theme": "default", "grade": "7th Grade", "skills": []} def save_settings(theme, grade, skills): settings["theme"] = theme settings["grade"] = grade settings["skills"] = skills.split(",") return f"โœ… Settings saved: {settings}" # -- UI -- with gr.Blocks() as app: with gr.Tab("๐Ÿ’ญ Solver + Image Upload"): img = gr.Image(label="๐Ÿ“ธ Upload Image", type="pil", sources=["upload"]) img_text = gr.Textbox(label="๐Ÿ” OCR Extracted", visible=False) question = gr.Textbox(label="โœ๏ธ Your Question") mode = gr.Radio(["๐Ÿ’ก Hint", "๐Ÿ”„ Steps", "โœ… Final"], label="Mode") response = gr.Textbox(label="๐Ÿค– AI Response") final = gr.Textbox(label="โœ… Final Answer") img.change(extract_and_fill, img, [img_text, question]) gr.Button("๐Ÿ’ญ Think For Me").click(solve_question, [question, mode], [response, final]) gr.Button("๐Ÿงน Clear").click(lambda: ("", "", "", ""), None, [question, response, final, img_text]) with gr.Tab("๐ŸŽฎ Game"): grade = gr.Dropdown(["3rd Grade", "4th Grade", "5th Grade", "6th Grade", "7th Grade"], label="Grade", value="7th Grade") gq = gr.Textbox(label="Question") gchoices = gr.Radio(label="Choices", choices=[]) gcorrect = gr.Textbox(visible=False) feedback = gr.Textbox(label="Feedback") gr.Button("๐ŸŽฒ New Question").click(generate_game_question, [grade], [gq, gchoices, gcorrect]) gr.Button("โœ… Submit").click(check_answer, [gchoices, gcorrect], feedback) gr.Button("๐Ÿงน Clear").click(lambda: ("", [], ""), None, [gq, gchoices, gcorrect]) with gr.Tab("๐Ÿ“˜ Smart Tutor"): sq = gr.Textbox(label="Question") satt = gr.Textbox(label="What did you try?") smode = gr.Radio(["๐Ÿ’ก Just a Hint", "โœ… Check My Work", "๐Ÿงญ Walk Me Through It", "๐Ÿ” Try a Similar Problem", "๐Ÿ“˜ Explain the Concept"], label="Mode") sconcept = gr.Textbox(label="Concept") sgrade = gr.Dropdown(["3rd Grade", "4th Grade", "5th Grade", "6th Grade", "7th Grade"], label="Grade", value="7th Grade") sres = gr.Textbox(label="Tutor Response") gr.Button("๐Ÿง  Tutor Me").click(smart_tutor, [sq, satt, smode, sconcept, sgrade], sres) gr.Button("๐Ÿงน Clear").click(lambda: ("", "", None, "", "", ""), None, [sq, satt, smode, sconcept, sgrade, sres]) with gr.Tab("๐Ÿงช AI Lab"): lq = gr.Textbox(label="Input") lmode = gr.Radio(["๐Ÿ” Predict Difficulty", "๐Ÿง  Classify Topic", "๐Ÿงช Create Practice Set", "๐Ÿง  Explain Confusion Point", "๐ŸŽฏ Make Similar Questions", "๐ŸŽ“ Estimate Grade Level", "๐Ÿ”ข Predict Step Count", "๐Ÿงฉ Extract Keywords", "๐Ÿšซ Common Mistakes"], label="Tool") lres = gr.Textbox(label="AI Output") gr.Button("Run AI Tool").click(ai_lab, [lq, lmode], lres) gr.Button("๐Ÿงน Clear").click(lambda: ("", None, ""), None, [lq, lmode, lres]) with gr.Tab("โš™๏ธ Settings"): theme = gr.Radio(["default", "soft", "compact"], label="Theme") default_grade = gr.Dropdown(["3rd Grade", "4th Grade", "5th Grade", "6th Grade", "7th Grade"], label="Default Grade") skills = gr.Textbox(label="Math Skills (comma separated)") saved = gr.Textbox(label="Saved Settings") gr.Button("๐Ÿ’พ Save Settings").click(save_settings, [theme, default_grade, skills], saved) gr.Button("๐Ÿงน Clear").click(lambda: (None, None, ""), None, [theme, default_grade, skills]) app.launch()