""" MwalimuAI - FINAL PRESENTATION VERSION Working Schemer tool with table output and reliable navigation. No JavaScript errors. Ready for demo. """ import gradio as gr import requests import os import json # =========================== # Configuration # =========================== # Get API token from environment API_TOKEN = os.getenv("HF_API_TOKEN") if not API_TOKEN: raise EnvironmentError("Set HF_API_TOKEN in your environment or Hugging Face Secrets") # Hugging Face Inference API for Gemma API_URL = "https://api-inference.huggingface.co/models/google/gemma-2b-it" headers = {"Authorization": f"Bearer {API_TOKEN}"} # =========================== # Tool Definitions # =========================== TOOLS = [ {"id": "lesson-plan", "name": "Lesson Plan Generator", "desc": "Create CBC-aligned lesson plans"}, {"id": "worksheet", "name": "Worksheet Generator", "desc": "Generate printable worksheets"}, {"id": "schemer", "name": "Schemer: Schemes of Work", "desc": "Create complete Schemes of Work"}, {"id": "quiz", "name": "Multiple Choice Quiz", "desc": "Generate quizzes and assessments"}, {"id": "rubric", "name": "Rubric Generator", "desc": "Create custom rubrics"}, {"id": "email", "name": "Email to Family", "desc": "Generate professional parent communications"} ] # =========================== # AI Backend (Gemma) # =========================== def query_gemma(prompt: str, max_tokens=1024) -> str: """Send prompt to Gemma and return response.""" try: response = requests.post( API_URL, headers=headers, json={ "inputs": prompt, "parameters": { "max_new_tokens": max_tokens, "temperature": 0.3, "top_p": 0.95, "do_sample": True } }, timeout=60 ) if response.status_code == 200: return response.json()[0]['generated_text'].strip() return f"Error: {response.status_code} - {response.text}" except Exception as e: return f"Request failed: {str(e)}" # =========================== # SCHEMER: Schemes of Work Creator (Table Format) # =========================== def create_schemer_interface(): """Create the Schemer interface with table output""" with gr.Column(): gr.Markdown("## Schemer: Schemes of Work Creator") gr.Markdown("Create CBC-compliant Schemes of Work in official table format") with gr.Row(): subject = gr.Dropdown( ["Mathematics", "English", "Kiswahili", "Science", "Social Studies"], label="Subject", value="Mathematics" ) grade = gr.Dropdown(list(range(1, 13)), label="Grade", value=4) sub_strand = gr.Textbox( label="Sub-Strand", placeholder="e.g., Numbers, Grammar, Living Things" ) with gr.Row(): num_weeks = gr.Slider(1, 8, value=6, step=1, label="Number of Weeks") num_lessons = gr.Slider(1, 5, value=3, step=1, label="Lessons per Week") resources = gr.Textbox( label="Available Resources", value="Chalkboard, basic materials", placeholder="e.g., Chalkboard, textbooks, charts" ) generate_btn = gr.Button("Generate Scheme of Work", variant="primary") output = gr.HTML() def generate_scheme(subj, grd, sub_strand_val, weeks, lessons, res): if not sub_strand_val.strip(): return "

Please enter a Sub-Strand.

" total_lessons = weeks * lessons prompt = f""" Create a CBC Scheme of Work for Grade {grd} {subj} with Sub-Strand: '{sub_strand_val}'. Duration: {weeks} weeks, {lessons} lessons per week ({total_lessons} total lessons). Format as a Markdown table with columns: | Week | Lesson | Sub-Strand | Lesson Learning Outcomes | Specific Learning Experiences | Key Inquiry Question | Learning Resources | Assessment | Requirements: 1. Week: 1-{weeks}, Lesson: 1-{lessons} per week 2. Lesson Learning Outcomes: Specific, measurable goals 3. Specific Learning Experiences: Include Knowledge, Skill, Attitude 4. Key Inquiry Question: One per lesson (Socratic style) 5. Learning Resources: Include local alternatives 6. Assessment: Appropriate method for each lesson 7. Use Kenyan context and examples 8. Ensure progression from simple to complex 9. Exactly {total_lessons} lessons Be concrete and actionable. """ ai_response = query_gemma(prompt) # Simple table conversion (works for most cases) if "|" in ai_response and "Week" in ai_response: lines = [line.strip() for line in ai_response.split('\n') if line.strip()] table_lines = [line for line in lines if "|" in line] if len(table_lines) > 1: headers = [h.strip() for h in table_lines[0].split('|')[1:-1]] html = """ """ + "".join([f"" for h in headers]) + "" for line in table_lines[1:]: cells = [c.strip() for c in line.split('|')[1:-1]] html += "" for cell in cells: html += f"" html += "" html += "
{h}
{cell}
" return html # Fallback for non-table responses return f"

Scheme of Work

{ai_response}

" generate_btn.click( generate_scheme, [subject, grade, sub_strand, num_weeks, num_lessons, resources], output ) return output # =========================== # MAIN INTERFACE (Simple Tabs) # =========================== with gr.Blocks( title="MwalimuAI - Teacher Tools", theme=gr.themes.Soft(), css=""" .main-title { font-size: 28px; font-weight: bold; margin-bottom: 20px; } table { border-collapse: collapse; width: 100%; margin: 15px 0; } th, td { border: 1px solid #ddd; padding: 10px; text-align: left; } th { background-color: #f8f9fa; } .tool-card { border: 1px solid #e0e0e0; padding: 15px; margin: 10px 0; border-radius: 8px; background: #f9f9f9; } """ ) as demo: gr.Markdown("

MwalimuAI - CBC Teaching Assistant

") gr.Markdown("Professional AI tools for Kenyan educators") with gr.Tabs(): # Dashboard Tab with gr.Tab("Dashboard"): gr.Markdown("### 🛠️ Teacher Tools") for tool in TOOLS: with gr.Group(elem_classes="tool-card"): gr.Markdown(f"**{tool['name']}**") gr.Markdown(f"{tool['desc']}") gr.Button(f"Open {tool['name']}", link=f"#{tool['id']}") # Individual Tool Tabs with gr.Tab("Schemer: Schemes of Work"): create_schemer_interface() with gr.Tab("Lesson Plan Generator"): gr.Markdown("## Lesson Plan Generator") gr.Markdown("Create CBC-aligned lesson plans") # Add your lesson plan interface here gr.Textbox("This is a placeholder for the Lesson Plan tool") with gr.Tab("Worksheet Generator"): gr.Markdown("## Worksheet Generator") gr.Markdown("Create printable worksheets") # Add your worksheet interface here gr.Textbox("This is a placeholder for the Worksheet tool") with gr.Tab("Multiple Choice Quiz"): gr.Markdown("## Multiple Choice Quiz Generator") gr.Markdown("Create quizzes and assessments") gr.Textbox("This is a placeholder for the Quiz tool") gr.Markdown("___") gr.Markdown("© 2025 MwalimuAI by SyncSenta. For authorized educational use in Kenyan classrooms.") # =========================== # LAUNCH # =========================== if __name__ == "__main__": try: demo.launch( server_name="0.0.0.0", server_port=7860, show_api=False, show_error=True, debug=False ) except Exception as e: print(f"Launch error: {e}") # Fallback with minimal settings demo.launch(share=True)