dgith commited on
Commit
500ecdc
·
verified ·
1 Parent(s): 7b78e0c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +317 -406
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, Tuple
 
 
 
 
8
 
9
- # Hugging Face Inference API setup
10
  API_URL = "https://api-inference.huggingface.co/models/google/gemma-2b-it"
11
- API_TOKEN = os.getenv("HF_API_TOKEN") # Set in Hugging Face Secrets
12
 
13
  if not API_TOKEN:
14
- raise EnvironmentError("HF_API_TOKEN not found. Please set it in Secrets.")
15
 
16
  headers = {"Authorization": f"Bearer {API_TOKEN}"}
17
 
18
- # CBC Curriculum Knowledge Base
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
- def query_gemma(prompt: str) -> str:
54
- """Send prompt to Gemma via Hugging Face Inference API"""
 
 
 
 
 
 
 
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 "⏳ Model is loading. Please wait 1-2 minutes and try again."
75
  if response.status_code == 429:
76
- return "⚠️ Too many requests. Please wait a moment."
77
- if response.status_code == 413:
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
- # Try to extract JSON if present
85
- json_start = output.find('{')
86
- json_end = output.rfind('}') + 1
87
- if json_start != -1 and json_end != -1:
88
  try:
89
- json_str = output[json_start:json_end]
90
- return json.loads(json_str)
91
  except json.JSONDecodeError:
92
  pass
93
-
94
- # Fallback: return raw text if no JSON
95
- return {"fallback_response": output}
96
-
97
- except requests.exceptions.RequestException as e:
98
- print(f"Network error: {str(e)}")
99
- return {"error": f"Network error: {str(e)}"}
100
  except Exception as e:
101
- print(f"Unexpected error: {str(e)}")
102
- return {"error": f"Error: {str(e)}"}
103
 
104
- def generate_lesson_plan_with_gemma(topic: str, grade: int, language: str, resources: str) -> Dict:
105
- """Generate lesson plan using Gemma with CBC context"""
106
-
 
 
 
 
 
 
 
107
  subject = categorize_subject(topic)
108
-
109
- # Create structured prompt for Gemma
110
  prompt = f"""
111
- You are MwalimuAI, a CBC lesson planning expert for Kenyan classrooms.
112
 
113
- Create a 40-minute lesson plan for Grade {grade} on "{topic}" in {language}.
114
 
115
- ### CBC CONTEXT
116
- - Grade {grade} → {'Lower Primary (1-3)' if grade <= 3 else 'Upper Primary (4-6)' if grade <= 6 else 'Secondary'}
117
  - Subject: {subject}
118
- - Materials: {resources}
119
  - Core CBC Competencies: {', '.join(CBC_COMPETENCIES)}
120
 
121
  ### INSTRUCTIONS
122
- 1. Return ONLY a JSON object with these exact fields:
123
  {{
124
- "objectives": ["3 specific, measurable learning objectives using action verbs"],
125
- "materials_needed": "Comma-separated list including local alternatives",
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 thought-provoking question for critical thinking",
134
  "differentiation": {{
135
- "slow_learners": "Concrete strategies for struggling students",
136
- "fast_learners": "Enrichment ideas for advanced learners"
137
  }},
138
- "competency_tags": ["CBC competency (Grade {grade})", "..."]
139
  }}
140
- 2. Total time must be exactly 40 minutes
141
- 3. Use Kenyan context and examples
142
- 4. Activities must be practical and hands-on
143
- 5. Objectives must be measurable
144
- 6. Return ONLY JSON - no additional text
145
- 7. If unsure, make reasonable assumptions
146
  """
147
-
148
  result = query_gemma(prompt)
149
-
150
  if "error" in result:
151
- # Fallback to rule-based
152
- return generate_lesson_plan_backend(topic, grade, language, resources)
153
-
154
- if isinstance(result, dict) and "fallback_response" in result:
155
- # Failed to parse JSON, use rule-based
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 (Competency Based Curriculum)",
165
  "generator": "MwalimuAI with Google Gemma-2b-it"
166
  }
167
-
168
  return result
169
 
170
- def generate_lesson_plan_backend(topic: str, grade: int, language: str, resources: str) -> Dict:
171
- """Fallback rule-based generator (kept for reliability)"""
172
- subject = categorize_subject(topic)
173
-
174
- # [Your existing fallback code - kept for reliability]
175
- objective_templates = {
176
- "Mathematics": [
177
- f"Apply mathematical concepts of {topic} to solve real-world problems",
178
- f"Demonstrate understanding of {topic} through practical activities",
179
- f"Use mathematical reasoning to explain {topic} solutions"
180
- ],
181
- "English": [
182
- f"Communicate effectively using {topic}",
183
- f"Demonstrate comprehension of {topic}",
184
- f"Apply {topic} language skills in practical contexts"
185
- ],
186
- "Science": [
187
- f"Investigate and explore {topic} through hands-on activities",
188
- f"Explain scientific concepts related to {topic}",
189
- f"Apply scientific method to understand {topic}"
190
- ],
191
- "Social Studies": [
192
- f"Analyze the importance of {topic} in society",
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": f"Warm-up song or game related to {topic}", "time": "5 min"},
211
- {"step": 2, "description": f"Show and tell about {topic} using pictures or real objects", "time": "8 min"},
212
- {"step": 3, "description": f"Hands-on activity with {topic} using {resources}", "time": "15 min"},
213
- {"step": 4, "description": "Simple group discussion - what did we learn?", "time": "7 min"},
214
- {"step": 5, "description": f"Drawing or coloring activity about {topic}", "time": "5 min"}
215
  ]
216
  elif grade <= 6:
217
  activities = [
218
- {"step": 1, "description": f"Brainstorm what we know about {topic}", "time": "5 min"},
219
- {"step": 2, "description": f"Introduce key concepts of {topic} with examples", "time": "10 min"},
220
- {"step": 3, "description": f"Practical investigation or experiment about {topic}", "time": "15 min"},
221
- {"step": 4, "description": f"Group work - solve problems related to {topic}", "time": "8 min"},
222
- {"step": 5, "description": "Present findings and discuss applications", "time": "2 min"}
223
  ]
224
  else:
225
  activities = [
226
- {"step": 1, "description": f"Review prior knowledge of {topic}", "time": "5 min"},
227
- {"step": 2, "description": f"Explain advanced concepts of {topic}", "time": "12 min"},
228
- {"step": 3, "description": f"Analytical activity or case study on {topic}", "time": "15 min"},
229
- {"step": 4, "description": "Critical thinking discussion and evaluation", "time": "6 min"},
230
- {"step": 5, "description": "Reflection and connection to real world", "time": "2 min"}
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": materials_needed,
259
  "activities": activities,
260
- "socratic_prompt": socratic_prompt,
261
  "differentiation": {
262
- "slow_learners": f"Provide visual aids, break {topic} into smaller steps, use peer support, give extra time for practice",
263
- "fast_learners": f"Challenge with extension questions about {topic}, leadership roles in group work, research additional applications"
264
  },
265
- "competency_tags": 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 (Competency Based Curriculum)",
272
- "generator": "MwalimuAI (Fallback)"
273
  }
274
  }
275
 
 
 
 
 
 
276
  def format_lesson_plan(lesson: Dict) -> str:
277
- """Format lesson plan for chat display"""
278
  if "error" in lesson:
279
- return f"❌ {lesson['error']}"
280
-
281
- if "fallback_response" in lesson:
282
- return f"⚠️ Using fallback response:\n\n{lesson['fallback_response']}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
 
284
- output = f"""
285
- # 📚 **Lesson Plan: {lesson['metadata']['topic']}**
286
- **Grade:** {lesson['metadata']['grade']} | **Generated:** {lesson['metadata']['generated_at']}
287
 
288
- ## 🎯 **Learning Objectives:**
289
- """
290
- for i, obj in enumerate(lesson.get('objectives', []), 1):
291
- output += f"{i}. {obj}\n"
292
-
293
- output += f"\n## 📦 **Materials Needed:**\n{lesson.get('materials_needed', 'Not specified')}\n"
294
-
295
- output += f"\n## 📋 **Activities (40 minutes total):**\n"
296
- for activity in lesson.get('activities', []):
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
- message_clean = message.lower()
321
-
322
- # Extract grade
323
- grade_patterns = [r'grade\s*(\d+)', r'class\s*(\d+)', r'standard\s*(\d+)']
324
- for pattern in grade_patterns:
325
- match = re.search(pattern, message_clean)
326
- if match:
327
- grade = int(match.group(1))
328
- if 1 <= grade <= 12:
329
- info['grade'] = grade
330
- break
331
-
332
- # Extract topic
333
- math_topics = ['addition', 'subtraction', 'fractions', 'numbers']
334
- english_topics = ['reading', 'writing', 'grammar', 'comprehension']
335
- science_topics = ['plants', 'animals', 'weather', 'science']
336
- social_topics = ['history', 'geography', 'culture', 'kenya']
337
-
338
- all_topics = math_topics + english_topics + science_topics + social_topics
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
- words = message.split()
351
- for word in words:
352
- if word.istitle() and len(word) > 3:
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
- def handle_lesson_request(self, message: str, history: List) -> str:
367
- """Handle lesson plan requests using Gemma"""
368
- info = self.extract_lesson_info(message)
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
- 💡 **Need modifications?** I can:
398
- - Adjust for different learning styles
399
- - Suggest alternative materials
400
- - Add assessment questions
401
- - Adapt for mixed-ability classes
402
 
403
- **What would you like to improve?**
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
- 👋 **Jambo! I'm MwalimuAI, your CBC lesson planning assistant powered by Google Gemma!**
413
-
414
- I create **high-quality, curriculum-aligned lesson plans** using Kenya's CBC framework.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
415
 
416
- **Just tell me:**
417
- - What topic you want to teach
418
- - Which grade
419
- - Any specific resources
420
 
421
- **Example requests:**
422
- - "Create a Grade 4 Mathematics lesson on Fractions"
423
- - "I need a Science lesson about Photosynthesis for Class 3"
 
 
424
 
425
- **What lesson shall we create today?** 📚✨
426
- """
427
-
428
- lesson_keywords = ['lesson', 'plan', 'teach', 'grade', 'topic', 'help', 'create']
429
- if any(kw in message_lower for kw in lesson_keywords):
430
- return self.handle_lesson_request(message, history)
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
- I'm here to help you create great lessons! 📚
476
- """
 
477
 
478
- # Initialize chatbot
479
- chatbot = MwalimuAIChatbot()
480
 
481
- # Create Gradio interface
482
  with gr.Blocks(
483
- title="🎓 MwalimuAI - CBC Lesson Planner",
484
  theme=gr.themes.Soft(),
485
- css="""
486
- .gradio-container {
487
- background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
488
- }
489
- """
490
- ) as demo:
491
-
492
- gr.Markdown("""
493
- # 🎓 MwalimuAI - CBC Lesson Planner
494
-
495
- **Your AI Teaching Assistant Powered by Google Gemma** 🇰🇪
496
-
497
- Get expert-level, CBC-aligned lesson plans created with AI!
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
- submit_btn = gr.Button("📤 Send", variant="primary")
508
- clear_btn = gr.Button("🗑️ Clear Chat")
509
-
510
  state = gr.State([])
511
-
512
- def user(message, history):
513
  return "", history + [[message, None]]
514
-
515
- def bot(history):
516
- response = chatbot.chat_response(history[-1][0], [h[0] for h in history[:-1]])
517
  history[-1][1] = response
518
  return history
519
-
520
- submit_btn.click(user, [msg, state], [msg, state], queue=False).then(bot, state, chatbot_component)
521
- msg.submit(user, [msg, state], [msg, state], queue=False).then(bot, state, chatbot_component)
522
- clear_btn.click(lambda: [], None, chatbot_component, queue=False)
523
-
 
 
 
 
524
  gr.Examples(
525
- examples=[
526
- "Create a Grade 4 lesson plan on Fractions",
527
- "I need help teaching Plants to Class 3",
528
- "Plan a Grade 6 English lesson on Creative Writing",
529
- "Adjust activities for different learning styles"
530
  ],
531
- inputs=msg
 
 
 
 
 
 
 
532
  )
533
-
534
- gr.Markdown("""
535
- ---
536
- ### 🌟 Features:
537
- - ✅ Powered by **Google Gemma-2b-it**
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
- demo.launch(server_name="0.0.0.0", server_port=7860, show_error=True)
 
 
 
 
 
 
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
+ )