Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,21 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
| 3 |
import os
|
| 4 |
-
import time
|
| 5 |
import re
|
| 6 |
import json
|
| 7 |
-
from typing import Dict, List
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
|
| 9 |
-
# Hugging Face Inference API
|
| 10 |
API_URL = "https://api-inference.huggingface.co/models/google/gemma-2b-it"
|
| 11 |
-
API_TOKEN = os.getenv("HF_API_TOKEN")
|
| 12 |
|
| 13 |
if not API_TOKEN:
|
| 14 |
-
raise EnvironmentError("HF_API_TOKEN
|
| 15 |
|
| 16 |
headers = {"Authorization": f"Bearer {API_TOKEN}"}
|
| 17 |
|
| 18 |
-
# CBC Curriculum
|
| 19 |
CBC_SUBJECTS = {
|
| 20 |
1: ["English", "Kiswahili", "Mathematics", "Environmental Activities", "Christian Religious Education", "Psychomotor and Creative Activities"],
|
| 21 |
2: ["English", "Kiswahili", "Mathematics", "Environmental Activities", "Christian Religious Education", "Psychomotor and Creative Activities"],
|
|
@@ -27,7 +36,7 @@ CBC_SUBJECTS = {
|
|
| 27 |
|
| 28 |
CBC_COMPETENCIES = [
|
| 29 |
"Communication and Collaboration",
|
| 30 |
-
"Critical Thinking and Problem Solving",
|
| 31 |
"Creativity and Imagination",
|
| 32 |
"Citizenship",
|
| 33 |
"Digital Literacy",
|
|
@@ -35,23 +44,16 @@ CBC_COMPETENCIES = [
|
|
| 35 |
"Self Efficacy"
|
| 36 |
]
|
| 37 |
|
| 38 |
-
def categorize_subject(topic: str) -> str:
|
| 39 |
-
"""Determine subject category from topic"""
|
| 40 |
-
topic_lower = topic.lower()
|
| 41 |
-
|
| 42 |
-
if any(word in topic_lower for word in ['add', 'subtract', 'multiply', 'divide', 'number', 'fraction', 'geometry', 'algebra', 'math']):
|
| 43 |
-
return "Mathematics"
|
| 44 |
-
elif any(word in topic_lower for word in ['read', 'write', 'story', 'poem', 'grammar', 'vocabulary', 'english']):
|
| 45 |
-
return "English"
|
| 46 |
-
elif any(word in topic_lower for word in ['science', 'plant', 'animal', 'experiment', 'nature', 'body', 'health', 'weather']):
|
| 47 |
-
return "Science"
|
| 48 |
-
elif any(word in topic_lower for word in ['history', 'geography', 'community', 'culture', 'government', 'social']):
|
| 49 |
-
return "Social Studies"
|
| 50 |
-
else:
|
| 51 |
-
return "General"
|
| 52 |
|
| 53 |
-
|
| 54 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
try:
|
| 56 |
response = requests.post(
|
| 57 |
API_URL,
|
|
@@ -68,61 +70,60 @@ def query_gemma(prompt: str) -> str:
|
|
| 68 |
},
|
| 69 |
timeout=60
|
| 70 |
)
|
| 71 |
-
|
| 72 |
-
# Handle common responses
|
| 73 |
if response.status_code == 503:
|
| 74 |
-
return "
|
| 75 |
if response.status_code == 429:
|
| 76 |
-
return "
|
| 77 |
-
|
| 78 |
-
return "❌ Prompt too long. Please shorten your request."
|
| 79 |
-
|
| 80 |
response.raise_for_status()
|
| 81 |
-
|
| 82 |
output = response.json()[0]['generated_text'].strip()
|
| 83 |
-
|
| 84 |
-
#
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
if
|
| 88 |
try:
|
| 89 |
-
|
| 90 |
-
return json.loads(json_str)
|
| 91 |
except json.JSONDecodeError:
|
| 92 |
pass
|
| 93 |
-
|
| 94 |
-
# Fallback: return raw text if
|
| 95 |
-
return {"
|
| 96 |
-
|
| 97 |
-
except requests.exceptions.
|
| 98 |
-
|
| 99 |
-
return {"error": f"Network error: {str(e)}"}
|
| 100 |
except Exception as e:
|
| 101 |
-
|
| 102 |
-
return {"error": f"Error: {str(e)}"}
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 107 |
subject = categorize_subject(topic)
|
| 108 |
-
|
| 109 |
-
# Create structured prompt for Gemma
|
| 110 |
prompt = f"""
|
| 111 |
-
You are MwalimuAI, a CBC
|
| 112 |
|
| 113 |
-
|
| 114 |
|
| 115 |
-
###
|
| 116 |
-
- Grade {grade} → {'Lower Primary (1
|
| 117 |
- Subject: {subject}
|
| 118 |
-
-
|
| 119 |
- Core CBC Competencies: {', '.join(CBC_COMPETENCIES)}
|
| 120 |
|
| 121 |
### INSTRUCTIONS
|
| 122 |
-
1. Return
|
| 123 |
{{
|
| 124 |
-
"objectives": ["
|
| 125 |
-
"materials_needed": "Comma-separated list
|
| 126 |
"activities": [
|
| 127 |
{{"step": 1, "description": "Detailed activity", "time": "X min"}},
|
| 128 |
{{"step": 2, "description": "Detailed activity", "time": "X min"}},
|
|
@@ -130,419 +131,329 @@ Create a 40-minute lesson plan for Grade {grade} on "{topic}" in {language}.
|
|
| 130 |
{{"step": 4, "description": "Detailed activity", "time": "X min"}},
|
| 131 |
{{"step": 5, "description": "Detailed activity", "time": "X min"}}
|
| 132 |
],
|
| 133 |
-
"socratic_prompt": "One
|
| 134 |
"differentiation": {{
|
| 135 |
-
"slow_learners": "
|
| 136 |
-
"fast_learners": "Enrichment
|
| 137 |
}},
|
| 138 |
-
"competency_tags": ["
|
| 139 |
}}
|
| 140 |
-
2. Total time must be exactly 40 minutes
|
| 141 |
-
3. Use Kenyan context and examples
|
| 142 |
-
4. Activities must be
|
| 143 |
-
5. Objectives must
|
| 144 |
-
6. Return
|
| 145 |
-
7. If
|
| 146 |
"""
|
| 147 |
-
|
| 148 |
result = query_gemma(prompt)
|
| 149 |
-
|
| 150 |
if "error" in result:
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
return generate_lesson_plan_backend(topic, grade, language, resources)
|
| 157 |
-
|
| 158 |
-
# Add metadata
|
| 159 |
result["metadata"] = {
|
| 160 |
-
"generated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
| 161 |
"grade": grade,
|
| 162 |
"topic": topic,
|
| 163 |
"language": language,
|
| 164 |
-
"curriculum": "CBC
|
| 165 |
"generator": "MwalimuAI with Google Gemma-2b-it"
|
| 166 |
}
|
| 167 |
-
|
| 168 |
return result
|
| 169 |
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
"
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
f"Demonstrate understanding of {topic} in Kenyan context",
|
| 194 |
-
f"Evaluate the impact of {topic} on community life"
|
| 195 |
-
]
|
| 196 |
-
}
|
| 197 |
-
|
| 198 |
-
if subject in objective_templates:
|
| 199 |
-
objectives = objective_templates[subject]
|
| 200 |
-
else:
|
| 201 |
-
objectives = [
|
| 202 |
-
f"Understand the key concepts of {topic}",
|
| 203 |
-
f"Apply knowledge of {topic} in practical situations",
|
| 204 |
-
f"Demonstrate learning of {topic} through active participation"
|
| 205 |
-
]
|
| 206 |
-
|
| 207 |
-
# Generate age-appropriate activities
|
| 208 |
if grade <= 3:
|
| 209 |
activities = [
|
| 210 |
-
{"step": 1, "description":
|
| 211 |
-
{"step": 2, "description":
|
| 212 |
-
{"step": 3, "description":
|
| 213 |
-
{"step": 4, "description": "
|
| 214 |
-
{"step": 5, "description":
|
| 215 |
]
|
| 216 |
elif grade <= 6:
|
| 217 |
activities = [
|
| 218 |
-
{"step": 1, "description":
|
| 219 |
-
{"step": 2, "description":
|
| 220 |
-
{"step": 3, "description":
|
| 221 |
-
{"step": 4, "description":
|
| 222 |
-
{"step": 5, "description": "
|
| 223 |
]
|
| 224 |
else:
|
| 225 |
activities = [
|
| 226 |
-
{"step": 1, "description":
|
| 227 |
-
{"step": 2, "description":
|
| 228 |
-
{"step": 3, "description":
|
| 229 |
-
{"step": 4, "description": "Critical
|
| 230 |
-
{"step": 5, "description": "
|
| 231 |
]
|
| 232 |
-
|
| 233 |
-
socratic_prompts = [
|
| 234 |
-
f"Why do you think {topic} is important in our daily lives?",
|
| 235 |
-
f"How would you explain {topic} to your younger sibling?",
|
| 236 |
-
f"What problems in our community could be solved using {topic}?",
|
| 237 |
-
f"If {topic} didn't exist, how would our lives be different?",
|
| 238 |
-
f"How does {topic} connect to what we learned last week?"
|
| 239 |
-
]
|
| 240 |
-
|
| 241 |
-
if grade <= 3:
|
| 242 |
-
socratic_prompts = [
|
| 243 |
-
f"What do you see when you think of {topic}?",
|
| 244 |
-
f"How do we use {topic} at home?",
|
| 245 |
-
f"What makes {topic} special?"
|
| 246 |
-
]
|
| 247 |
-
|
| 248 |
-
socratic_prompt = socratic_prompts[0]
|
| 249 |
-
|
| 250 |
-
local_materials = ["manila paper", "markers", "locally available items", "charts", "real objects from environment"]
|
| 251 |
-
materials_needed = f"{resources}, {', '.join(local_materials[:2])}"
|
| 252 |
-
|
| 253 |
-
competencies = CBC_COMPETENCIES[:3]
|
| 254 |
-
competency_tags = [f"{comp} (Grade {grade})" for comp in competencies]
|
| 255 |
-
|
| 256 |
return {
|
| 257 |
"objectives": objectives,
|
| 258 |
-
"materials_needed":
|
| 259 |
"activities": activities,
|
| 260 |
-
"socratic_prompt":
|
| 261 |
"differentiation": {
|
| 262 |
-
"slow_learners":
|
| 263 |
-
"fast_learners":
|
| 264 |
},
|
| 265 |
-
"competency_tags":
|
| 266 |
"metadata": {
|
| 267 |
-
"generated_at": time.strftime("%Y-%m-%d %H:%M:%S"),
|
| 268 |
"grade": grade,
|
| 269 |
"topic": topic,
|
| 270 |
"language": language,
|
| 271 |
-
"curriculum": "CBC
|
| 272 |
-
"generator": "MwalimuAI (Fallback)"
|
| 273 |
}
|
| 274 |
}
|
| 275 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 276 |
def format_lesson_plan(lesson: Dict) -> str:
|
| 277 |
-
"""
|
| 278 |
if "error" in lesson:
|
| 279 |
-
return f"
|
| 280 |
-
|
| 281 |
-
if "
|
| 282 |
-
return f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
-
output = f"""
|
| 285 |
-
# 📚 **Lesson Plan: {lesson['metadata']['topic']}**
|
| 286 |
-
**Grade:** {lesson['metadata']['grade']} | **Generated:** {lesson['metadata']['generated_at']}
|
| 287 |
|
| 288 |
-
#
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
output += f"**Step {activity['step']}** ({activity['time']}): {activity['description']}\n"
|
| 298 |
-
|
| 299 |
-
output += f"\n## 🤔 **Socratic Question:**\n*{lesson.get('socratic_prompt', 'Not specified')}*\n"
|
| 300 |
-
|
| 301 |
-
diff = lesson.get('differentiation', {})
|
| 302 |
-
output += f"\n## 👥 **Differentiation:**\n"
|
| 303 |
-
output += f"**Slow Learners:** {diff.get('slow_learners', 'Not specified')}\n"
|
| 304 |
-
output += f"**Fast Learners:** {diff.get('fast_learners', 'Not specified')}\n"
|
| 305 |
-
|
| 306 |
-
output += f"\n## ✅ **CBC Competencies:**\n"
|
| 307 |
-
for competency in lesson.get('competency_tags', []):
|
| 308 |
-
output += f"• {competency}\n"
|
| 309 |
-
|
| 310 |
-
return output
|
| 311 |
-
|
| 312 |
-
# Chatbot Logic
|
| 313 |
-
class MwalimuAIChatbot:
|
| 314 |
-
def __init__(self):
|
| 315 |
-
self.conversation_state = {}
|
| 316 |
-
|
| 317 |
-
def extract_lesson_info(self, message: str) -> Dict:
|
| 318 |
-
"""Extract lesson planning information from user message"""
|
| 319 |
info = {}
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
#
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
if
|
| 327 |
-
grade =
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
for topic in all_topics:
|
| 341 |
-
if topic in message_clean:
|
| 342 |
-
info['topic'] = topic.title()
|
| 343 |
break
|
| 344 |
-
|
| 345 |
if 'topic' not in info:
|
| 346 |
quoted = re.findall(r'"([^"]*)"', message)
|
| 347 |
if quoted:
|
| 348 |
info['topic'] = quoted[0]
|
| 349 |
else:
|
| 350 |
-
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
info['topic'] = word
|
| 354 |
-
break
|
| 355 |
-
|
| 356 |
-
# Resources
|
| 357 |
-
resource_keywords = ['chalkboard', 'projector', 'books', 'materials']
|
| 358 |
-
mentioned = [w for w in resource_keywords if w in message_clean]
|
| 359 |
-
info['resources'] = ', '.join(mentioned).title() if mentioned else "Chalkboard, basic materials"
|
| 360 |
-
|
| 361 |
-
# Language
|
| 362 |
-
info['language'] = 'sw' if any(w in message_clean for w in ['swahili', 'kiswahili']) else 'en'
|
| 363 |
-
|
| 364 |
-
return info
|
| 365 |
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
missing_info = []
|
| 371 |
-
if 'topic' not in info: missing_info.append('topic')
|
| 372 |
-
if 'grade' not in info: missing_info.append('grade')
|
| 373 |
-
|
| 374 |
-
if missing_info:
|
| 375 |
-
return f"""
|
| 376 |
-
🤔 I'd love to help! Please specify the **{' and '.join(missing_info)}**.
|
| 377 |
-
|
| 378 |
-
**Examples:**
|
| 379 |
-
- "Create a Grade 4 lesson on Fractions"
|
| 380 |
-
- "Plan a Science lesson for Class 3 about Plants"
|
| 381 |
-
"""
|
| 382 |
-
|
| 383 |
-
lesson = generate_lesson_plan_with_gemma(
|
| 384 |
-
topic=info['topic'],
|
| 385 |
-
grade=info['grade'],
|
| 386 |
-
language=info['language'],
|
| 387 |
-
resources=info['resources']
|
| 388 |
-
)
|
| 389 |
-
|
| 390 |
-
formatted_plan = format_lesson_plan(lesson)
|
| 391 |
-
|
| 392 |
-
return f"""
|
| 393 |
-
✅ **CBC-Aligned Lesson Plan Created!**
|
| 394 |
-
|
| 395 |
-
{formatted_plan}
|
| 396 |
|
| 397 |
-
|
| 398 |
-
|
| 399 |
-
- Suggest alternative materials
|
| 400 |
-
- Add assessment questions
|
| 401 |
-
- Adapt for mixed-ability classes
|
| 402 |
|
| 403 |
-
|
| 404 |
-
"""
|
|
|
|
| 405 |
|
| 406 |
-
def chat_response(self, message: str, history: List) -> str:
|
| 407 |
-
"""Main chat response handler"""
|
| 408 |
-
message_lower = message.lower()
|
| 409 |
-
|
| 410 |
if not history:
|
| 411 |
-
return
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
|
| 420 |
|
| 421 |
-
|
| 422 |
-
|
| 423 |
-
|
|
|
|
|
|
|
| 424 |
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
| 431 |
-
|
| 432 |
-
cbc_keywords = ['cbc', 'curriculum', 'competency', 'syllabus']
|
| 433 |
-
if any(kw in message_lower for kw in cbc_keywords):
|
| 434 |
-
return """
|
| 435 |
-
📖 **About Kenya's CBC:**
|
| 436 |
-
Focuses on 7 core competencies:
|
| 437 |
-
1. Communication & Collaboration
|
| 438 |
-
2. Critical Thinking
|
| 439 |
-
3. Creativity
|
| 440 |
-
4. Citizenship
|
| 441 |
-
5. Digital Literacy
|
| 442 |
-
6. Learning to Learn
|
| 443 |
-
7. Self Efficacy
|
| 444 |
-
|
| 445 |
-
Want a lesson plan demonstrating these? Just ask!
|
| 446 |
-
"""
|
| 447 |
-
|
| 448 |
-
help_keywords = ['help', 'how', 'what', 'can you']
|
| 449 |
-
if any(kw in message_lower for kw in help_keywords):
|
| 450 |
-
return """
|
| 451 |
-
🎯 **I create CBC lesson plans using Google's Gemma AI!**
|
| 452 |
-
|
| 453 |
-
**Tell me:**
|
| 454 |
-
- Topic to teach
|
| 455 |
-
- Grade level
|
| 456 |
-
- Available resources
|
| 457 |
-
|
| 458 |
-
I'll generate a complete 40-minute plan with:
|
| 459 |
-
✅ Learning objectives
|
| 460 |
-
✅ Step-by-step activities
|
| 461 |
-
✅ Differentiation strategies
|
| 462 |
-
✅ Socratic questions
|
| 463 |
-
|
| 464 |
-
**Try:** "Create a Grade 3 lesson on Addition"
|
| 465 |
-
"""
|
| 466 |
-
|
| 467 |
-
return """
|
| 468 |
-
🤔 **I specialize in CBC lesson planning.**
|
| 469 |
|
| 470 |
-
Could you clarify if you'd like:
|
| 471 |
-
1. A new lesson plan? (Tell me topic and grade)
|
| 472 |
-
2. Help with CBC curriculum?
|
| 473 |
-
3. Modifications to an existing plan?
|
| 474 |
|
| 475 |
-
|
| 476 |
-
|
|
|
|
| 477 |
|
| 478 |
-
|
| 479 |
-
chatbot = MwalimuAIChatbot()
|
| 480 |
|
| 481 |
-
# Create Gradio interface
|
| 482 |
with gr.Blocks(
|
| 483 |
-
title="
|
| 484 |
theme=gr.themes.Soft(),
|
| 485 |
-
css=""
|
| 486 |
-
|
| 487 |
-
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 494 |
-
|
| 495 |
-
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
""")
|
| 499 |
-
|
| 500 |
-
chatbot_component = gr.Chatbot(height=500)
|
| 501 |
-
msg = gr.Textbox(
|
| 502 |
-
placeholder="Ask me to create a lesson plan! E.g., 'Grade 4 Mathematics on Fractions'",
|
| 503 |
-
container=False
|
| 504 |
)
|
| 505 |
-
|
| 506 |
with gr.Row():
|
| 507 |
-
|
| 508 |
-
|
| 509 |
-
|
| 510 |
state = gr.State([])
|
| 511 |
-
|
| 512 |
-
def
|
| 513 |
return "", history + [[message, None]]
|
| 514 |
-
|
| 515 |
-
def
|
| 516 |
-
response =
|
| 517 |
history[-1][1] = response
|
| 518 |
return history
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 524 |
gr.Examples(
|
| 525 |
-
|
| 526 |
-
"Create a Grade 4 lesson
|
| 527 |
-
"
|
| 528 |
-
"
|
| 529 |
-
"Adjust activities for different learning styles"
|
| 530 |
],
|
| 531 |
-
inputs=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 532 |
)
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
- 🎯 CBC-aligned lesson plans
|
| 539 |
-
- ⏰ 40-minute structured activities
|
| 540 |
-
- 👥 Differentiation strategies
|
| 541 |
-
- 📦 Local resource suggestions
|
| 542 |
-
|
| 543 |
-
**Made with ❤️ for Kenyan Teachers**
|
| 544 |
-
""")
|
| 545 |
-
|
| 546 |
-
# Launch
|
| 547 |
if __name__ == "__main__":
|
| 548 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
MwalimuAI Lesson Planner
|
| 3 |
+
A professional CBC-aligned lesson planning assistant powered by Google Gemma.
|
| 4 |
+
Built for deployment on Hugging Face Spaces with clean, enterprise-grade UX.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
import gradio as gr
|
| 8 |
import requests
|
| 9 |
import os
|
|
|
|
| 10 |
import re
|
| 11 |
import json
|
| 12 |
+
from typing import Dict, List
|
| 13 |
+
|
| 14 |
+
# ===========================
|
| 15 |
+
# Configuration & Initialization
|
| 16 |
+
# ===========================
|
| 17 |
|
| 18 |
+
# Hugging Face Inference API endpoint for Google Gemma-2b-it
|
| 19 |
API_URL = "https://api-inference.huggingface.co/models/google/gemma-2b-it"
|
| 20 |
+
API_TOKEN = os.getenv("HF_API_TOKEN")
|
| 21 |
|
| 22 |
if not API_TOKEN:
|
| 23 |
+
raise EnvironmentError("Critical: HF_API_TOKEN is missing. Please configure it in deployment secrets.")
|
| 24 |
|
| 25 |
headers = {"Authorization": f"Bearer {API_TOKEN}"}
|
| 26 |
|
| 27 |
+
# CBC Curriculum Framework
|
| 28 |
CBC_SUBJECTS = {
|
| 29 |
1: ["English", "Kiswahili", "Mathematics", "Environmental Activities", "Christian Religious Education", "Psychomotor and Creative Activities"],
|
| 30 |
2: ["English", "Kiswahili", "Mathematics", "Environmental Activities", "Christian Religious Education", "Psychomotor and Creative Activities"],
|
|
|
|
| 36 |
|
| 37 |
CBC_COMPETENCIES = [
|
| 38 |
"Communication and Collaboration",
|
| 39 |
+
"Critical Thinking and Problem Solving",
|
| 40 |
"Creativity and Imagination",
|
| 41 |
"Citizenship",
|
| 42 |
"Digital Literacy",
|
|
|
|
| 44 |
"Self Efficacy"
|
| 45 |
]
|
| 46 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
+
# ===========================
|
| 49 |
+
# Core AI Integration
|
| 50 |
+
# ===========================
|
| 51 |
+
|
| 52 |
+
def query_gemma(prompt: str) -> dict:
|
| 53 |
+
"""
|
| 54 |
+
Sends a structured prompt to Gemma via Hugging Face Inference API.
|
| 55 |
+
Returns parsed JSON response or fallback indicator.
|
| 56 |
+
"""
|
| 57 |
try:
|
| 58 |
response = requests.post(
|
| 59 |
API_URL,
|
|
|
|
| 70 |
},
|
| 71 |
timeout=60
|
| 72 |
)
|
| 73 |
+
|
|
|
|
| 74 |
if response.status_code == 503:
|
| 75 |
+
return {"error": "Model is currently loading. Please try again in 1–2 minutes."}
|
| 76 |
if response.status_code == 429:
|
| 77 |
+
return {"error": "Rate limit exceeded. Please wait before submitting another request."}
|
| 78 |
+
|
|
|
|
|
|
|
| 79 |
response.raise_for_status()
|
|
|
|
| 80 |
output = response.json()[0]['generated_text'].strip()
|
| 81 |
+
|
| 82 |
+
# Attempt to extract JSON
|
| 83 |
+
start = output.find('{')
|
| 84 |
+
end = output.rfind('}') + 1
|
| 85 |
+
if start != -1 and end != -1:
|
| 86 |
try:
|
| 87 |
+
return json.loads(output[start:end])
|
|
|
|
| 88 |
except json.JSONDecodeError:
|
| 89 |
pass
|
| 90 |
+
|
| 91 |
+
# Fallback: return raw text if JSON parsing fails
|
| 92 |
+
return {"raw_response": output}
|
| 93 |
+
|
| 94 |
+
except requests.exceptions.Timeout:
|
| 95 |
+
return {"error": "Request timed out. Please try again."}
|
|
|
|
| 96 |
except Exception as e:
|
| 97 |
+
return {"error": f"Request failed: {str(e)}"}
|
|
|
|
| 98 |
|
| 99 |
+
|
| 100 |
+
# ===========================
|
| 101 |
+
# Lesson Plan Generation
|
| 102 |
+
# ===========================
|
| 103 |
+
|
| 104 |
+
def generate_lesson_plan(topic: str, grade: int, language: str, resources: str) -> Dict:
|
| 105 |
+
"""
|
| 106 |
+
Generates a CBC-aligned lesson plan using Gemma.
|
| 107 |
+
Falls back to rule-based logic if AI fails.
|
| 108 |
+
"""
|
| 109 |
subject = categorize_subject(topic)
|
| 110 |
+
|
|
|
|
| 111 |
prompt = f"""
|
| 112 |
+
You are MwalimuAI, a CBC curriculum expert for Kenyan classrooms.
|
| 113 |
|
| 114 |
+
Generate a 40-minute lesson plan for Grade {grade} on "{topic}" in {language}.
|
| 115 |
|
| 116 |
+
### CONTEXT
|
| 117 |
+
- Grade {grade} → {'Lower Primary (1–3)' if grade <= 3 else 'Upper Primary (4–6)' if grade <= 6 else 'Secondary'}
|
| 118 |
- Subject: {subject}
|
| 119 |
+
- Available Resources: {resources}
|
| 120 |
- Core CBC Competencies: {', '.join(CBC_COMPETENCIES)}
|
| 121 |
|
| 122 |
### INSTRUCTIONS
|
| 123 |
+
1. Return only a JSON object with these fields:
|
| 124 |
{{
|
| 125 |
+
"objectives": ["Specific, measurable learning goals"],
|
| 126 |
+
"materials_needed": "Comma-separated list with local alternatives",
|
| 127 |
"activities": [
|
| 128 |
{{"step": 1, "description": "Detailed activity", "time": "X min"}},
|
| 129 |
{{"step": 2, "description": "Detailed activity", "time": "X min"}},
|
|
|
|
| 131 |
{{"step": 4, "description": "Detailed activity", "time": "X min"}},
|
| 132 |
{{"step": 5, "description": "Detailed activity", "time": "X min"}}
|
| 133 |
],
|
| 134 |
+
"socratic_prompt": "One open-ended critical thinking question",
|
| 135 |
"differentiation": {{
|
| 136 |
+
"slow_learners": "Practical support strategies",
|
| 137 |
+
"fast_learners": "Enrichment and extension ideas"
|
| 138 |
}},
|
| 139 |
+
"competency_tags": ["Competency (Grade {grade})", "..."]
|
| 140 |
}}
|
| 141 |
+
2. Total time must be exactly 40 minutes.
|
| 142 |
+
3. Use Kenyan context and real-world examples.
|
| 143 |
+
4. Activities must be hands-on and learner-centered.
|
| 144 |
+
5. Objectives must use action verbs.
|
| 145 |
+
6. Return only JSON — no additional text.
|
| 146 |
+
7. If uncertain, make reasonable pedagogical assumptions.
|
| 147 |
"""
|
| 148 |
+
|
| 149 |
result = query_gemma(prompt)
|
| 150 |
+
|
| 151 |
if "error" in result:
|
| 152 |
+
return generate_fallback_lesson_plan(topic, grade, language, resources)
|
| 153 |
+
|
| 154 |
+
if "raw_response" in result:
|
| 155 |
+
return generate_fallback_lesson_plan(topic, grade, language, resources)
|
| 156 |
+
|
|
|
|
|
|
|
|
|
|
| 157 |
result["metadata"] = {
|
|
|
|
| 158 |
"grade": grade,
|
| 159 |
"topic": topic,
|
| 160 |
"language": language,
|
| 161 |
+
"curriculum": "CBC",
|
| 162 |
"generator": "MwalimuAI with Google Gemma-2b-it"
|
| 163 |
}
|
| 164 |
+
|
| 165 |
return result
|
| 166 |
|
| 167 |
+
|
| 168 |
+
def categorize_subject(topic: str) -> str:
|
| 169 |
+
"""Maps topic to CBC subject area."""
|
| 170 |
+
topic_lower = topic.lower()
|
| 171 |
+
if any(w in topic_lower for w in ['math', 'add', 'subtract', 'fraction']):
|
| 172 |
+
return "Mathematics"
|
| 173 |
+
if any(w in topic_lower for w in ['english', 'read', 'write', 'grammar']):
|
| 174 |
+
return "English"
|
| 175 |
+
if any(w in topic_lower for w in ['science', 'plant', 'animal', 'weather']):
|
| 176 |
+
return "Science"
|
| 177 |
+
if any(w in topic_lower for w in ['social', 'history', 'geography', 'culture']):
|
| 178 |
+
return "Social Studies"
|
| 179 |
+
return "General"
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def generate_fallback_lesson_plan(topic: str, grade: int, language: str, resources: str) -> Dict:
|
| 183 |
+
"""Fallback rule-based generator for reliability."""
|
| 184 |
+
objectives = [
|
| 185 |
+
f"Understand the key concepts of {topic}",
|
| 186 |
+
f"Apply knowledge of {topic} in practical situations",
|
| 187 |
+
f"Participate actively in {topic}-related activities"
|
| 188 |
+
]
|
| 189 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 190 |
if grade <= 3:
|
| 191 |
activities = [
|
| 192 |
+
{"step": 1, "description": "Warm-up game related to the topic", "time": "5 min"},
|
| 193 |
+
{"step": 2, "description": "Teacher demonstration with visuals", "time": "8 min"},
|
| 194 |
+
{"step": 3, "description": "Hands-on group activity", "time": "15 min"},
|
| 195 |
+
{"step": 4, "description": "Group discussion", "time": "7 min"},
|
| 196 |
+
{"step": 5, "description": "Creative reflection activity", "time": "5 min"}
|
| 197 |
]
|
| 198 |
elif grade <= 6:
|
| 199 |
activities = [
|
| 200 |
+
{"step": 1, "description": "Review prior knowledge", "time": "5 min"},
|
| 201 |
+
{"step": 2, "description": "Introduce key concepts", "time": "10 min"},
|
| 202 |
+
{"step": 3, "description": "Guided investigation", "time": "15 min"},
|
| 203 |
+
{"step": 4, "description": "Group problem-solving", "time": "8 min"},
|
| 204 |
+
{"step": 5, "description": "Class presentation", "time": "2 min"}
|
| 205 |
]
|
| 206 |
else:
|
| 207 |
activities = [
|
| 208 |
+
{"step": 1, "description": "Review previous lesson", "time": "5 min"},
|
| 209 |
+
{"step": 2, "description": "Explain advanced concepts", "time": "12 min"},
|
| 210 |
+
{"step": 3, "description": "Case study analysis", "time": "15 min"},
|
| 211 |
+
{"step": 4, "description": "Critical discussion", "time": "6 min"},
|
| 212 |
+
{"step": 5, "description": "Real-world application", "time": "2 min"}
|
| 213 |
]
|
| 214 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 215 |
return {
|
| 216 |
"objectives": objectives,
|
| 217 |
+
"materials_needed": f"{resources}, charts, locally available items",
|
| 218 |
"activities": activities,
|
| 219 |
+
"socratic_prompt": f"How does {topic} apply to everyday life in Kenya?",
|
| 220 |
"differentiation": {
|
| 221 |
+
"slow_learners": "Use visual aids and peer support.",
|
| 222 |
+
"fast_learners": "Assign leadership roles and extension tasks."
|
| 223 |
},
|
| 224 |
+
"competency_tags": [f"{CBC_COMPETENCIES[i]} (Grade {grade})" for i in range(3)],
|
| 225 |
"metadata": {
|
|
|
|
| 226 |
"grade": grade,
|
| 227 |
"topic": topic,
|
| 228 |
"language": language,
|
| 229 |
+
"curriculum": "CBC",
|
| 230 |
+
"generator": "MwalimuAI (Rule-Based Fallback)"
|
| 231 |
}
|
| 232 |
}
|
| 233 |
|
| 234 |
+
|
| 235 |
+
# ===========================
|
| 236 |
+
# Formatting & Response Logic
|
| 237 |
+
# ===========================
|
| 238 |
+
|
| 239 |
def format_lesson_plan(lesson: Dict) -> str:
|
| 240 |
+
"""Formats the lesson plan for clean display."""
|
| 241 |
if "error" in lesson:
|
| 242 |
+
return f"**Error**: {lesson['error']}"
|
| 243 |
+
|
| 244 |
+
if "raw_response" in lesson:
|
| 245 |
+
return f"**Note**: Using fallback content.\n\n{lesson['raw_response']}"
|
| 246 |
+
|
| 247 |
+
lines = [
|
| 248 |
+
f"**Lesson Plan: {lesson['metadata']['topic']}**",
|
| 249 |
+
f"**Grade**: {lesson['metadata']['grade']}",
|
| 250 |
+
"",
|
| 251 |
+
"**Learning Objectives:**",
|
| 252 |
+
*(f"{i}. {obj}" for i, obj in enumerate(lesson.get('objectives', []), 1)),
|
| 253 |
+
"",
|
| 254 |
+
"**Materials Needed:**",
|
| 255 |
+
lesson.get('materials_needed', 'Not specified'),
|
| 256 |
+
"",
|
| 257 |
+
"**Lesson Activities (40 minutes):**",
|
| 258 |
+
*(f"Step {act['step']} ({act['time']}): {act['description']}" for act in lesson.get('activities', [])),
|
| 259 |
+
"",
|
| 260 |
+
"**Socratic Question:**",
|
| 261 |
+
f"→ {lesson.get('socratic_prompt', 'Not specified')}",
|
| 262 |
+
"",
|
| 263 |
+
"**Differentiation Strategies:**",
|
| 264 |
+
f"• **Support for Struggling Learners:** {lesson['differentiation'].get('slow_learners', 'Not specified')}",
|
| 265 |
+
f"• **Enrichment for Advanced Learners:** {lesson['differentiation'].get('fast_learners', 'Not specified')}",
|
| 266 |
+
"",
|
| 267 |
+
"**Aligned CBC Competencies:**",
|
| 268 |
+
*(f"• {tag}" for tag in lesson.get('competency_tags', []))
|
| 269 |
+
]
|
| 270 |
+
return "\n".join(lines)
|
| 271 |
|
|
|
|
|
|
|
|
|
|
| 272 |
|
| 273 |
+
# ===========================
|
| 274 |
+
# Chatbot Business Logic
|
| 275 |
+
# ===========================
|
| 276 |
+
|
| 277 |
+
class MwalimuAIBot:
|
| 278 |
+
"""Main chatbot interface with clean conversation flow."""
|
| 279 |
+
|
| 280 |
+
def extract_info(self, message: str) -> Dict:
|
| 281 |
+
"""Extracts topic, grade, and resources from user input."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 282 |
info = {}
|
| 283 |
+
msg_lower = message.lower()
|
| 284 |
+
|
| 285 |
+
# Grade
|
| 286 |
+
match = re.search(r'grade\s*(\d+)|class\s*(\d+)|standard\s*(\d+)', msg_lower)
|
| 287 |
+
if match:
|
| 288 |
+
grade = int(match.group(1) or match.group(2) or match.group(3))
|
| 289 |
+
if 1 <= grade <= 12:
|
| 290 |
+
info['grade'] = grade
|
| 291 |
+
|
| 292 |
+
# Topic keywords
|
| 293 |
+
topics = {
|
| 294 |
+
'math': ['math', 'add', 'fraction', 'number'],
|
| 295 |
+
'english': ['english', 'read', 'write', 'grammar'],
|
| 296 |
+
'science': ['science', 'plant', 'animal', 'experiment'],
|
| 297 |
+
'social': ['social', 'history', 'geography', 'culture']
|
| 298 |
+
}
|
| 299 |
+
for key, words in topics.items():
|
| 300 |
+
if any(word in msg_lower for word in words):
|
| 301 |
+
info['topic'] = key.replace('_', ' ').title()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 302 |
break
|
| 303 |
+
|
| 304 |
if 'topic' not in info:
|
| 305 |
quoted = re.findall(r'"([^"]*)"', message)
|
| 306 |
if quoted:
|
| 307 |
info['topic'] = quoted[0]
|
| 308 |
else:
|
| 309 |
+
capitalized = [w for w in message.split() if w.istitle() and len(w) > 3]
|
| 310 |
+
if capitalized:
|
| 311 |
+
info['topic'] = capitalized[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 312 |
|
| 313 |
+
info['resources'] = "Chalkboard, basic materials"
|
| 314 |
+
if any(r in msg_lower for r in ['projector', 'books', 'computer']):
|
| 315 |
+
info['resources'] += ", " + ", ".join([r for r in ['projector', 'books', 'computer'] if r in msg_lower])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 316 |
|
| 317 |
+
info['language'] = 'sw' if 'swahili' in msg_lower else 'en'
|
| 318 |
+
return info
|
|
|
|
|
|
|
|
|
|
| 319 |
|
| 320 |
+
def respond(self, message: str, history: List) -> str:
|
| 321 |
+
"""Main response handler."""
|
| 322 |
+
msg_lower = message.lower()
|
| 323 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 324 |
if not history:
|
| 325 |
+
return (
|
| 326 |
+
"Welcome to **MwalimuAI**, your intelligent assistant for creating "
|
| 327 |
+
"CBC-aligned lesson plans for Kenyan classrooms.\n\n"
|
| 328 |
+
"To get started, please specify:\n"
|
| 329 |
+
"- The **topic** you wish to teach\n"
|
| 330 |
+
"- The **grade level**\n\n"
|
| 331 |
+
"Example: *Create a Grade 4 lesson on Fractions*"
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
if any(kw in msg_lower for kw in ['lesson', 'plan', 'teach', 'grade', 'topic']):
|
| 335 |
+
return self.handle_lesson_request(message)
|
| 336 |
+
|
| 337 |
+
if any(kw in msg_lower for kw in ['cbc', 'curriculum', 'competency']):
|
| 338 |
+
return (
|
| 339 |
+
"**Competency-Based Curriculum (CBC)** emphasizes:\n"
|
| 340 |
+
"• Learner-centered instruction\n"
|
| 341 |
+
"• Practical, hands-on learning\n"
|
| 342 |
+
"• Development of 7 core competencies\n"
|
| 343 |
+
"• Continuous assessment\n\n"
|
| 344 |
+
"Would you like a lesson plan demonstrating CBC principles?"
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
if any(kw in msg_lower for kw in ['help', 'how', 'what']):
|
| 348 |
+
return (
|
| 349 |
+
"**MwalimuAI** generates complete 40-minute lesson plans aligned with CBC.\n\n"
|
| 350 |
+
"Features:\n"
|
| 351 |
+
"• Clear learning objectives\n"
|
| 352 |
+
"• Step-by-step classroom activities\n"
|
| 353 |
+
"• Differentiation strategies\n"
|
| 354 |
+
"• Socratic questioning\n"
|
| 355 |
+
"• Resource optimization\n\n"
|
| 356 |
+
"Try: *Create a Grade 3 lesson on Addition*"
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
return (
|
| 360 |
+
"I specialize in creating CBC-aligned lesson plans.\n\n"
|
| 361 |
+
"Please specify:\n"
|
| 362 |
+
"- The **topic** you'd like to teach\n"
|
| 363 |
+
"- The **grade level**\n\n"
|
| 364 |
+
"I will generate a complete, ready-to-use lesson plan."
|
| 365 |
+
)
|
| 366 |
|
| 367 |
+
def handle_lesson_request(self, message: str) -> str:
|
| 368 |
+
"""Processes lesson creation requests."""
|
| 369 |
+
info = self.extract_info(message)
|
| 370 |
+
missing = [f for f in ['topic', 'grade'] if f not in info]
|
| 371 |
|
| 372 |
+
if missing:
|
| 373 |
+
return (
|
| 374 |
+
f"Please specify the **{', '.join(missing)}**.\n\n"
|
| 375 |
+
"Example: *Create a Grade 4 Mathematics lesson on Fractions*"
|
| 376 |
+
)
|
| 377 |
|
| 378 |
+
lesson = generate_lesson_plan(
|
| 379 |
+
topic=info['topic'],
|
| 380 |
+
grade=info['grade'],
|
| 381 |
+
language=info['language'],
|
| 382 |
+
resources=info['resources']
|
| 383 |
+
)
|
| 384 |
+
return format_lesson_plan(lesson)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 385 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 386 |
|
| 387 |
+
# ===========================
|
| 388 |
+
# Gradio Interface
|
| 389 |
+
# ===========================
|
| 390 |
|
| 391 |
+
bot = MwalimuAIBot()
|
|
|
|
| 392 |
|
|
|
|
| 393 |
with gr.Blocks(
|
| 394 |
+
title="MwalimuAI Lesson Planner",
|
| 395 |
theme=gr.themes.Soft(),
|
| 396 |
+
css=".gradio-container { max-width: 800px; margin: auto; }"
|
| 397 |
+
) as interface:
|
| 398 |
+
|
| 399 |
+
gr.Markdown(
|
| 400 |
+
"# MwalimuAI\n"
|
| 401 |
+
"## CBC Lesson Planning Assistant\n"
|
| 402 |
+
"A professional AI tool for Kenyan educators"
|
| 403 |
+
)
|
| 404 |
+
|
| 405 |
+
chatbot = gr.Chatbot(height=500, label="Lesson Planning Console")
|
| 406 |
+
message_input = gr.Textbox(
|
| 407 |
+
placeholder="Enter your lesson request (e.g., 'Grade 4 lesson on Fractions')",
|
| 408 |
+
show_label=False
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 409 |
)
|
| 410 |
+
|
| 411 |
with gr.Row():
|
| 412 |
+
submit_button = gr.Button("Submit Request", variant="primary")
|
| 413 |
+
clear_button = gr.Button("Clear Conversation")
|
| 414 |
+
|
| 415 |
state = gr.State([])
|
| 416 |
+
|
| 417 |
+
def user_action(message, history):
|
| 418 |
return "", history + [[message, None]]
|
| 419 |
+
|
| 420 |
+
def bot_action(history):
|
| 421 |
+
response = bot.respond(history[-1][0], [h[0] for h in history[:-1]])
|
| 422 |
history[-1][1] = response
|
| 423 |
return history
|
| 424 |
+
|
| 425 |
+
submit_button.click(user_action, [message_input, state], [message_input, state]).then(
|
| 426 |
+
bot_action, state, chatbot
|
| 427 |
+
)
|
| 428 |
+
message_input.submit(user_action, [message_input, state], [message_input, state]).then(
|
| 429 |
+
bot_action, state, chatbot
|
| 430 |
+
)
|
| 431 |
+
clear_button.click(lambda: [], None, chatbot)
|
| 432 |
+
|
| 433 |
gr.Examples(
|
| 434 |
+
[
|
| 435 |
+
"Create a Grade 4 lesson on Fractions",
|
| 436 |
+
"Plan a Science lesson for Class 3 about Plants",
|
| 437 |
+
"I need a Grade 6 English lesson on Creative Writing"
|
|
|
|
| 438 |
],
|
| 439 |
+
inputs=message_input,
|
| 440 |
+
label="Sample Requests"
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
gr.Markdown(
|
| 444 |
+
"___\n"
|
| 445 |
+
"© 2025 MwalimuAI. For authorized educational use only.\n"
|
| 446 |
+
"Powered by Google Gemma and Hugging Face."
|
| 447 |
)
|
| 448 |
+
|
| 449 |
+
# ===========================
|
| 450 |
+
# Launch Application
|
| 451 |
+
# ===========================
|
| 452 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 453 |
if __name__ == "__main__":
|
| 454 |
+
interface.launch(
|
| 455 |
+
server_name="0.0.0.0",
|
| 456 |
+
server_port=7860,
|
| 457 |
+
show_api=False,
|
| 458 |
+
show_error=True
|
| 459 |
+
)
|