Turbiling commited on
Commit
7a2ee97
·
verified ·
1 Parent(s): 847f808

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +332 -478
app.py CHANGED
@@ -12,8 +12,7 @@ import re
12
  # Initialize Groq client with error handling
13
  try:
14
  client = Groq()
15
- # Test the client
16
- print("✓ Groq client initialized successfully")
17
  except Exception as e:
18
  print(f"Warning: Groq client initialization failed: {e}")
19
  client = None
@@ -47,31 +46,6 @@ ASSESSMENT_TYPES = [
47
  "Peer Assessment", "Self Assessment", "Portfolio Assessment"
48
  ]
49
 
50
- BLOOM_LEVELS = {
51
- "Knowledge": ["Remember", "Recall", "Define", "List", "Identify", "Label"],
52
- "Understanding": ["Explain", "Describe", "Summarize", "Interpret", "Compare", "Classify"],
53
- "Application": ["Apply", "Demonstrate", "Solve", "Calculate", "Use", "Implement"],
54
- "Analysis": ["Analyze", "Differentiate", "Organize", "Examine", "Investigate"],
55
- "Evaluation": ["Evaluate", "Assess", "Critique", "Justify", "Recommend"],
56
- "Creation": ["Create", "Design", "Develop", "Compose", "Construct"]
57
- }
58
-
59
- # Urdu translations for key terms
60
- URDU_TRANSLATIONS = {
61
- "Grade": "درجہ",
62
- "Subject": "مضمون",
63
- "Topic": "موضوع",
64
- "Teacher": "استاد",
65
- "School": "اسکول",
66
- "District": "ضلع",
67
- "Date": "تاریخ",
68
- "Students": "طلبہ کی تعداد",
69
- "Duration": "دورانیہ",
70
- "minutes": "منٹ",
71
- "Teaching Method": "تدریسی طریقہ",
72
- "Assessment": "تشخیص"
73
- }
74
-
75
  def update_subjects(grade_range):
76
  """Update subject dropdown based on grade selection"""
77
  if not grade_range:
@@ -115,32 +89,6 @@ def add_table_border(table):
115
  tblBorders.append(border)
116
  tblPr.append(tblBorders)
117
 
118
- def format_document_header(doc, language):
119
- """Create professional document header"""
120
- # Main header
121
- header = doc.add_paragraph()
122
- run = header.add_run("Government of Gilgit-Baltistan\n")
123
- run.bold = True
124
- run.font.size = Pt(16)
125
- run.font.color.rgb = RGBColor(0, 100, 0)
126
-
127
- run2 = header.add_run("School Education Department")
128
- run2.bold = True
129
- run2.font.size = Pt(14)
130
- run2.font.color.rgb = RGBColor(0, 100, 0)
131
- header.alignment = WD_ALIGN_PARAGRAPH.CENTER
132
-
133
- # Subtitle
134
- subheader = doc.add_paragraph()
135
- run = subheader.add_run("SMART LESSON PLAN")
136
- run.bold = True
137
- run.font.size = Pt(13)
138
- run.underline = True
139
- subheader.alignment = WD_ALIGN_PARAGRAPH.CENTER
140
- subheader.space_after = Pt(16)
141
-
142
- return doc
143
-
144
  def generate_lesson_plan(language, grade_range, grade_specific, subject, topic,
145
  school_name, teacher_name, district, date_input,
146
  students, duration, teaching_method, assessment_type,
@@ -149,12 +97,12 @@ def generate_lesson_plan(language, grade_range, grade_specific, subject, topic,
149
  # Validate inputs
150
  validation_errors = validate_inputs(language, grade_range, subject, topic, teacher_name, school_name)
151
  if validation_errors:
152
- error_msg = "⚠️ Please fix the following errors:\n" + "\n".join(f"• {e}" for e in validation_errors)
153
  return None, error_msg
154
 
155
  # Check if client is initialized
156
  if client is None:
157
- return None, "❌ Error: Groq API client not initialized. Please check your API key."
158
 
159
  # Format date
160
  if date_input:
@@ -170,7 +118,7 @@ def generate_lesson_plan(language, grade_range, grade_specific, subject, topic,
170
  if grade_specific:
171
  full_grade = grade_specific
172
  else:
173
- full_grade = grade_range.split('-')[0] # Default to first grade in range
174
 
175
  # Calculate time allocations
176
  intro_time = int(duration * 0.15)
@@ -178,10 +126,11 @@ def generate_lesson_plan(language, grade_range, grade_specific, subject, topic,
178
  conclusion_time = int(duration * 0.15)
179
  assessment_time = duration - (intro_time + main_time + conclusion_time)
180
 
181
- # Build enhanced prompt
182
- prompt = f"""You are an expert Pakistani educator and curriculum specialist with deep knowledge of the National Curriculum Framework, modern pedagogical approaches, and classroom management in Gilgit-Baltistan context.
 
183
 
184
- Create a COMPREHENSIVE, PRACTICAL, and STUDENT-CENTERED SMART LESSON PLAN in {language} language.
185
 
186
  **LESSON DETAILS:**
187
  - Grade: {full_grade}
@@ -198,143 +147,184 @@ Create a COMPREHENSIVE, PRACTICAL, and STUDENT-CENTERED SMART LESSON PLAN in {la
198
 
199
  **CRITICAL INSTRUCTIONS:**
200
 
201
- 1. **DO NOT repeat the information table in text format** - it will be added automatically.
202
-
203
- 2. **SMART STUDENT LEARNING OUTCOMES (SLOs):**
204
- Write EXACTLY THREE SLOs following Bloom's Taxonomy. Each must be:
205
- - **SLO 1 (Knowledge Level):** Start with verbs like: Define, List, Identify, Recall, State, Name
206
- - **SLO 2 (Understanding Level):** Start with verbs like: Explain, Describe, Summarize, Interpret, Compare, Discuss
207
- - **SLO 3 (Application Level):** Start with verbs like: Apply, Demonstrate, Solve, Calculate, Use, Illustrate
208
-
209
- Format each SLO as: "By the end of this lesson, students will be able to [action verb] [specific content] [condition/criteria]."
210
-
211
- Make SLOs:
212
- - Specific and measurable
213
- - Achievable within {duration} minutes
214
- - Aligned with National Curriculum standards
215
- - Observable and assessable
216
-
217
- 3. **CONTENT KNOWLEDGE:**
218
- Provide comprehensive subject content organized under clear subheadings:
219
- - **Key Concepts:** Main ideas students must understand
220
- - **Definitions:** Important terms with simple explanations
221
- - **Facts & Information:** Essential knowledge for this topic
222
- - **Prior Knowledge Required:** What students should already know
223
- - **Common Misconceptions:** Typical errors students make and how to address them
224
- - **Real-World Connections:** How this topic relates to daily life in Gilgit-Baltistan
225
-
226
- 4. **DETAILED LESSON PROCEDURE:**
227
-
228
- **A) INTRODUCTION/WARM-UP ({intro_time} minutes):**
229
- - Engaging hook or attention-grabber relevant to local context
230
- - Activity to activate prior knowledge
231
- - Clear statement of learning objectives in student-friendly language
232
- - Pre-assessment question to gauge understanding
233
-
234
- **B) MAIN TEACHING & LEARNING ACTIVITIES ({main_time} minutes):**
235
-
236
- *Teacher Activity:*
237
- - Step-by-step explanation using {teaching_method}
238
- - Clear examples with local/cultural relevance
239
- - Visual aids and demonstrations to use
240
- - Key questions to ask students
241
- - Checking for understanding strategies
242
-
243
- *Student Activity:*
244
- - Guided practice tasks (teacher support)
245
- - Independent practice activities
246
- - Group work or pair activities (if applicable)
247
- - Hands-on activities or experiments
248
- - Problem-solving tasks
249
-
250
- **C) ASSESSMENT & EVALUATION ({assessment_time} minutes):**
251
- - {assessment_type} activity description
252
- - Specific questions to assess each SLO
253
- - Success criteria for student performance
254
- - How to provide immediate feedback
255
-
256
- **D) CONCLUSION/CLOSURE ({conclusion_time} minutes):**
257
- - Summary of key learning points
258
- - Student reflection questions
259
- - Connection to next lesson
260
- - Preview of home assignment
261
-
262
- 5. **TEACHING RESOURCES & MATERIALS:**
263
- {"List all materials needed: textbooks, worksheets, charts, models, technology, stationery, etc. Be specific and practical for local school context." if include_resources else ""}
264
-
265
- 6. **DIFFERENTIATION STRATEGIES:**
266
- {"Provide specific strategies for:\n - **Advanced Learners:** Extension activities and challenging tasks\n - **Struggling Students:** Scaffolding techniques and simplified tasks\n - **Visual Learners:** Charts, diagrams, videos\n - **Kinesthetic Learners:** Hands-on activities and movement\n - **English Language Learners:** Vocabulary support and bilingual strategies" if include_differentiation else ""}
267
-
268
- 7. **HOME ASSIGNMENT:**
269
- Create a meaningful assignment that:
270
- - Directly reinforces the three SLOs
271
- - Is appropriate for {full_grade} level
272
- - Can be completed independently in 20-30 minutes
273
- - Has clear, step-by-step instructions
274
- - Includes success criteria or rubric
275
- - Encourages family involvement where appropriate
276
-
277
- 8. **TEACHER'S REFLECTION NOTES:**
278
- Add blank section with prompts:
279
- - What worked well in this lesson?
280
- - What challenges did students face?
281
- - Which students need additional support?
282
- - What would I change next time?
283
- - How well were SLOs achieved?
284
-
285
- **FORMATTING & LANGUAGE GUIDELINES:**
286
- {"For English version:" if language == "English" else "اردو کے لیے:"}
287
- - Use clear, professional language appropriate for educational documentation
288
  - Write in complete sentences and paragraphs
289
- - Use bullet points ONLY for lists of items or steps
290
- - Use proper headings hierarchy (Main headings bold and larger)
291
- - Maintain logical flow between sections
292
- - Be specific and practical, not vague or generic
293
- - Include culturally relevant examples from Gilgit-Baltistan context
294
- - {"Proper English grammar and spelling" if language == "English" else "صحیح اردو رسم الخط اور املا، دائیں سے بائیں سمت"}
295
 
296
- **OUTPUT FORMAT:**
297
- Generate ONLY the lesson plan content starting from "SMART STUDENT LEARNING OUTCOMES (SLOs)".
298
- Do NOT include any table or repeat the lesson details (Grade, Subject, etc.) as that will be added automatically.
299
- Do NOT add any developer credits, signatures, or metadata at the end.
300
 
301
- Now generate the complete, ready-to-implement lesson plan:"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
302
 
303
  try:
304
- # Generate content using Groq API with streaming
305
- print("🔄 Generating lesson plan with Groq API...")
306
 
307
  completion = client.chat.completions.create(
308
  model="openai/gpt-oss-120b",
309
  messages=[
310
  {
311
  "role": "system",
312
- "content": "You are an expert Pakistani educator and curriculum specialist. Generate comprehensive, professional lesson plans following the exact format and requirements provided."
313
  },
314
  {
315
  "role": "user",
316
  "content": prompt
317
  }
318
  ],
319
- temperature=0.7, # Slightly lower for more consistent educational content
320
  max_completion_tokens=8192,
321
  top_p=0.95,
322
- reasoning_effort="high", # Use high reasoning for better educational content
323
  stream=True,
324
  stop=None
325
  )
326
 
327
- # Collect the streamed response
328
  lesson_text = ""
329
  for chunk in completion:
330
  if chunk.choices[0].delta.content:
331
  lesson_text += chunk.choices[0].delta.content
332
 
333
  lesson_text = lesson_text.strip()
334
- print(f"✓ Generated {len(lesson_text)} characters")
335
 
336
- # Remove any accidental inclusion of lesson details from AI response
337
- lesson_text = re.sub(r'^.*?(SMART|SLO)', r'\1', lesson_text, flags=re.DOTALL | re.IGNORECASE)
338
 
339
  # Create Word document
340
  doc = Document()
@@ -348,14 +338,31 @@ Now generate the complete, ready-to-implement lesson plan:"""
348
  section.right_margin = Inches(0.75)
349
 
350
  if language == "English":
351
- # Professional header
352
- doc = format_document_header(doc, language)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
353
 
354
- # Information table with enhanced styling
355
  table = doc.add_table(rows=6, cols=4)
356
  add_table_border(table)
357
 
358
- # Header row styling
359
  def style_cell(cell, text, bold=False, bg_color=None):
360
  cell.text = text
361
  if bold:
@@ -368,7 +375,7 @@ Now generate the complete, ready-to-implement lesson plan:"""
368
  shading_elm.set(qn('w:fill'), bg_color)
369
  cell._element.get_or_add_tcPr().append(shading_elm)
370
 
371
- # Fill table with data
372
  cells = table.rows[0].cells
373
  style_cell(cells[0], "Grade", bold=True, bg_color="E7E6E6")
374
  style_cell(cells[1], full_grade)
@@ -404,9 +411,9 @@ Now generate the complete, ready-to-implement lesson plan:"""
404
  merged_cell = cells[1].merge(cells[3])
405
  style_cell(merged_cell, assessment_type)
406
 
407
- doc.add_paragraph() # Spacing
408
 
409
- # Process lesson content with enhanced formatting
410
  lines = lesson_text.split("\n")
411
 
412
  for line in lines:
@@ -414,19 +421,10 @@ Now generate the complete, ready-to-implement lesson plan:"""
414
  if not line_stripped:
415
  continue
416
 
417
- # Detect main headings
418
  is_main_heading = any(keyword in line_stripped.upper() for keyword in
419
  ["SMART STUDENT LEARNING OUTCOMES", "CONTENT KNOWLEDGE",
420
- "LESSON PROCEDURE", "TEACHING RESOURCES",
421
- "DIFFERENTIATION STRATEGIES", "HOME ASSIGNMENT",
422
- "TEACHER'S REFLECTION", "REFLECTION NOTES"])
423
-
424
- # Detect sub-headings
425
- is_sub_heading = any(keyword in line_stripped.upper() for keyword in
426
- ["INTRODUCTION", "WARM-UP", "MAIN TEACHING",
427
- "ASSESSMENT", "EVALUATION", "CONCLUSION", "CLOSURE",
428
- "KEY CONCEPTS", "DEFINITIONS", "PRIOR KNOWLEDGE",
429
- "TEACHER ACTIVITY", "STUDENT ACTIVITY"])
430
 
431
  # Detect SLOs
432
  is_slo = line_stripped.upper().startswith("SLO") or re.match(r'^(SLO\s*[1-3]|BY THE END)', line_stripped.upper())
@@ -438,88 +436,118 @@ Now generate the complete, ready-to-implement lesson plan:"""
438
  if is_main_heading:
439
  para.runs[0].bold = True
440
  para.runs[0].font.size = Pt(12)
441
- para.runs[0].font.color.rgb = RGBColor(0, 70, 130)
442
  para.paragraph_format.space_before = Pt(12)
443
  para.paragraph_format.space_after = Pt(8)
444
- elif is_sub_heading:
445
- para.runs[0].bold = True
446
- para.runs[0].font.size = Pt(11)
447
- para.runs[0].font.color.rgb = RGBColor(0, 100, 180)
448
- para.paragraph_format.space_before = Pt(8)
449
  elif is_slo:
450
  para.runs[0].bold = True
451
- para.runs[0].font.color.rgb = RGBColor(139, 0, 0)
452
  para.paragraph_format.left_indent = Inches(0.25)
453
 
454
- # Professional footer
455
  doc.add_paragraph()
456
- separator = doc.add_paragraph("_" * 80)
457
  separator.alignment = WD_ALIGN_PARAGRAPH.CENTER
 
458
 
459
- footer = doc.add_paragraph()
460
- run = footer.add_run(f"Generated: {datetime.now().strftime('%d %B %Y at %H:%M')} | ")
461
- run.font.size = Pt(8)
462
- run.font.italic = True
463
- run.font.color.rgb = RGBColor(100, 100, 100)
464
-
465
- run2 = footer.add_run("SMART Lesson Plan Generator v2.1 (Powered by Groq AI)")
466
- run2.font.size = Pt(8)
467
- run2.font.italic = True
468
- run2.font.color.rgb = RGBColor(100, 100, 100)
469
- footer.alignment = WD_ALIGN_PARAGRAPH.CENTER
470
-
471
- # Save file with descriptive name
472
  safe_topic = re.sub(r'[^\w\s-]', '', topic).strip()[:30]
473
  file_path = f"/tmp/LP_{subject}_{safe_topic}_{full_grade}_{formatted_date}.docx"
474
  doc.save(file_path)
475
 
476
- status_msg = f"""✅ **Lesson Plan Generated Successfully!**
477
 
478
- 📄 **File Details:**
479
  - Subject: {subject}
480
  - Grade: {full_grade}
481
  - Topic: {topic}
482
  - Duration: {duration} minutes
483
  - Date: {formatted_date}
484
 
485
- 💾 **File Name:** {os.path.basename(file_path)}
486
 
487
- ✨ **Next Steps:**
488
- 1. Download the file using the button below
489
- 2. Review and customize as needed
490
- 3. Print or share with colleagues
491
- 4. Use in your classroom!
492
 
493
- 🎯 **Quality Assurance:**
494
- - ✓ SMART SLOs aligned with Bloom's Taxonomy
495
- - ✓ Detailed lesson procedure with timings
496
- - ✓ Assessment strategies included
497
- - ✓ {('Teaching resources listed' if include_resources else 'Differentiation strategies added' if include_differentiation else 'Complete lesson plan')}
498
- - ✓ Home assignment provided
499
-
500
- 🤖 **Powered by:** Groq AI (openai/gpt-oss-120b)"""
501
 
502
- else: # Urdu version
503
  # Create Urdu document
504
  doc = Document()
505
 
506
- # Urdu header
507
  header = doc.add_paragraph()
508
  run = header.add_run("حکومت گلگت بلتستان\nمحکمہ تعلیم")
509
  run.bold = True
510
- run.font.size = Pt(16)
511
- run.font.color.rgb = RGBColor(0, 100, 0)
512
  header.alignment = WD_ALIGN_PARAGRAPH.CENTER
513
  header.paragraph_format.right_to_left = True
514
 
515
- subheader = doc.add_paragraph()
516
- run = subheader.add_run("اسمارٹ سبق کا منصوبہ")
 
517
  run.bold = True
518
  run.font.size = Pt(14)
519
  run.underline = True
520
- subheader.alignment = WD_ALIGN_PARAGRAPH.CENTER
521
- subheader.paragraph_format.right_to_left = True
522
- subheader.space_after = Pt(16)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
523
 
524
  # Add Urdu lesson content
525
  for line in lesson_text.split("\n"):
@@ -529,47 +557,59 @@ Now generate the complete, ready-to-implement lesson plan:"""
529
  para.paragraph_format.right_to_left = True
530
  para.paragraph_format.space_after = Pt(6)
531
  para.paragraph_format.line_spacing = 1.5
 
 
 
 
 
 
 
532
 
 
 
 
 
 
 
 
533
  safe_topic = re.sub(r'[^\w\s-]', '', topic).strip()[:30]
534
  file_path = f"/tmp/LP_Urdu_{safe_topic}_{formatted_date}.docx"
535
  doc.save(file_path)
536
 
537
- status_msg = f"""✅ **سبق کا منصوبہ تیار ہو گیا!**
538
 
539
- 📄 **تفصیلات:**
540
  - مضمون: {subject}
541
  - درجہ: {full_grade}
542
  - موضوع: {topic}
543
 
544
- 💾 فائل: {os.path.basename(file_path)}
545
 
546
- 🤖 **تیار کردہ بذریعہ:** Groq AI"""
 
 
 
547
 
548
  return file_path, status_msg
549
 
550
  except Exception as e:
551
- error_details = f"""❌ **Error Generating Lesson Plan**
552
-
553
- **Error Type:** {type(e).__name__}
554
- **Details:** {str(e)}
555
 
556
- **Troubleshooting Steps:**
557
- 1. Check your internet connection
558
- 2. Verify Groq API key is configured (GROQ_API_KEY environment variable)
559
- 3. Ensure all required fields are filled
560
- 4. Try again with a simpler topic
561
- 5. Check if you have sufficient API credits
562
 
563
- **API Configuration:**
564
- - Set your Groq API key: `export GROQ_API_KEY=your_api_key_here`
565
- - Get your API key from: https://console.groq.com/
 
 
566
 
567
- **If problem persists:** Contact technical support"""
568
 
569
  return None, error_details
570
 
571
 
572
- # Create Professional Gradio Interface
573
  custom_css = """
574
  .gradio-container {
575
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
@@ -588,244 +628,150 @@ custom_css = """
588
  margin: 1.5rem 0 1rem 0;
589
  border-radius: 5px;
590
  }
591
- .info-box {
592
- background-color: #e3f2fd;
593
- padding: 1rem;
594
- border-radius: 5px;
595
- border-left: 4px solid #2196f3;
596
- margin: 1rem 0;
597
- }
598
  """
599
 
600
- with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, title="SMART Lesson Plan Generator - GB Education") as demo:
601
 
602
- # Header with branding
603
  with gr.Row():
604
  gr.HTML("""
605
  <div class="main-header">
606
- <h1 style="margin:0; font-size: 2.5rem;">📚 SMART Lesson Plan Generator</h1>
607
  <p style="margin: 0.5rem 0 0 0; font-size: 1.1rem; opacity: 0.9;">
608
  Professional Lesson Planning Tool for Gilgit-Baltistan Schools
609
  </p>
610
  <p style="margin: 0.3rem 0 0 0; font-size: 0.9rem; opacity: 0.8;">
611
- Powered by Groq AI (openai/gpt-oss-120b) | Developed by Najaf Ali Sharqi
612
  </p>
613
  </div>
614
  """)
615
 
616
- # Information box
617
- with gr.Row():
618
- gr.Markdown("""
619
- <div class="info-box">
620
- <strong>🎯 About This Tool:</strong> Generate comprehensive, curriculum-aligned SMART lesson plans in English or Urdu.
621
- All plans include SMART SLOs based on Bloom's Taxonomy, detailed procedures, assessments, and home assignments.
622
- <br><br>
623
- <strong>🤖 AI Model:</strong> Using Groq's openai/gpt-oss-120b for high-quality, fast lesson plan generation.
624
- </div>
625
- """)
626
-
627
- # Main form sections
628
- gr.HTML('<div class="section-header"><h3>📋 Basic Lesson Information</h3></div>')
629
 
630
  with gr.Row():
631
  language = gr.Dropdown(
632
  choices=["English", "Urdu"],
633
- label="📝 Language",
634
  value="English",
635
- info="Select lesson plan language",
636
  interactive=True
637
  )
638
  grade_range = gr.Dropdown(
639
  choices=["Grade 1-5", "Grade 6-8", "Grade 9-10", "Grade 11-12"],
640
- label="🎓 Grade Range",
641
- info="Select grade level range",
642
  interactive=True
643
  )
644
  grade_specific = gr.Dropdown(
645
  choices=[f"Grade {i}" for i in range(1, 13)],
646
- label="📊 Specific Grade (Optional)",
647
- info="Select exact grade level",
648
  interactive=True
649
  )
650
 
651
  with gr.Row():
652
  subject = gr.Dropdown(
653
  choices=[],
654
- label="📖 Subject",
655
- info="Will update based on grade selection",
656
  interactive=True
657
  )
658
  topic = gr.Textbox(
659
- label="📌 Lesson Topic",
660
- placeholder="e.g., Photosynthesis, Pythagorean Theorem, Parts of Speech...",
661
- info="Enter the specific topic for this lesson",
662
  lines=1
663
  )
664
 
665
- gr.HTML('<div class="section-header"><h3>👨‍🏫 School & Teacher Details</h3></div>')
666
 
667
  with gr.Row():
668
  school_name = gr.Textbox(
669
- label="🏫 School Name",
670
  placeholder="e.g., Government High School Gilgit",
671
- info="Enter complete school name",
672
  lines=1
673
  )
674
  teacher_name = gr.Textbox(
675
- label="👤 Teacher Name",
676
  placeholder="e.g., Muhammad Ali Khan",
677
- info="Enter teacher's full name",
678
  lines=1
679
  )
680
  district = gr.Dropdown(
681
  choices=DISTRICTS_GB,
682
- label="📍 District",
683
  value="Gilgit",
684
- info="Select district in Gilgit-Baltistan",
685
  interactive=True
686
  )
687
 
688
- gr.HTML('<div class="section-header"><h3>⏰ Class Details & Timing</h3></div>')
689
 
690
  with gr.Row():
691
  date_input = gr.Textbox(
692
- label="📅 Lesson Date",
693
  value=datetime.now().strftime("%Y-%m-%d"),
694
- placeholder="YYYY-MM-DD",
695
- info="Enter date in YYYY-MM-DD format"
696
  )
697
  students = gr.Number(
698
- label="👥 Number of Students",
699
  value=35,
700
  minimum=1,
701
  maximum=100,
702
- step=1,
703
- info="Total students in the class"
704
  )
705
  duration = gr.Dropdown(
706
  choices=[35, 40, 45, 50, 60, 70, 80, 90],
707
- label="⏱️ Duration (minutes)",
708
  value=40,
709
- info="Total lesson duration",
710
  interactive=True
711
  )
712
 
713
- gr.HTML('<div class="section-header"><h3>🎯 Teaching Methodology & Assessment</h3></div>')
714
 
715
  with gr.Row():
716
  teaching_method = gr.Dropdown(
717
  choices=TEACHING_METHODS,
718
- label="🎓 Primary Teaching Method",
719
  value="Lecture Method",
720
- info="Main instructional approach for this lesson",
721
  interactive=True
722
  )
723
  assessment_type = gr.Dropdown(
724
  choices=ASSESSMENT_TYPES,
725
- label="📊 Assessment Method",
726
  value="Formative Assessment",
727
- info="How will you evaluate student learning?",
728
  interactive=True
729
  )
730
 
731
- gr.HTML('<div class="section-header"><h3>⚙️ Additional Options</h3></div>')
732
 
733
  with gr.Row():
734
- with gr.Column(scale=1):
735
- include_resources = gr.Checkbox(
736
- label="📦 Include Teaching Resources List",
737
- value=True,
738
- info="Add detailed list of required materials and resources"
739
- )
740
- with gr.Column(scale=1):
741
- include_differentiation = gr.Checkbox(
742
- label="🎯 Include Differentiation Strategies",
743
- value=True,
744
- info="Add strategies for diverse learners (advanced, struggling, special needs)"
745
- )
746
 
747
  gr.Markdown("---")
748
 
749
- # Generate button with styling
750
  generate_btn = gr.Button(
751
- "🚀 Generate SMART Lesson Plan",
752
  variant="primary",
753
- size="lg",
754
- scale=2
755
  )
756
 
757
- # Instructions
758
- with gr.Accordion("📖 Instructions & Tips", open=False):
759
- gr.Markdown("""
760
- ### How to Use This Generator:
761
-
762
- 1. **Select Language**: Choose English or Urdu for your lesson plan
763
- 2. **Choose Grade**: Select grade range, then specific grade if needed
764
- 3. **Select Subject**: Will auto-populate based on grade level
765
- 4. **Enter Topic**: Be specific (e.g., "Photosynthesis in Plants" not just "Science")
766
- 5. **Fill School Info**: Enter your school name and your name
767
- 6. **Set Class Details**: Number of students, date, and duration
768
- 7. **Choose Methods**: Select teaching and assessment approaches
769
- 8. **Click Generate**: Wait 10-20 seconds for AI to create your plan
770
-
771
- ### 💡 Tips for Best Results:
772
-
773
- - **Be Specific**: Instead of "Math", use "Linear Equations" or "Fractions"
774
- - **Realistic Duration**: Match duration to your actual class period
775
- - **Consider Context**: Choose methods suitable for your classroom resources
776
- - **Review & Edit**: Always review and customize the generated plan
777
- - **Save Multiple**: Generate variations to compare approaches
778
-
779
- ### ✨ What You'll Get:
780
-
781
- - **3 SMART SLOs** aligned with Bloom's Taxonomy (Knowledge, Understanding, Application)
782
- - **Comprehensive Content Knowledge** with key concepts and misconceptions
783
- - **Detailed Lesson Procedure** with exact timings for each phase
784
- - **Teaching Resources** list (if enabled)
785
- - **Differentiation Strategies** for diverse learners (if enabled)
786
- - **SMART Home Assignment** aligned with SLOs
787
- - **Reflection Section** for post-lesson notes
788
-
789
- ### 🎓 About SMART SLOs:
790
-
791
- SMART stands for:
792
- - **S**pecific: Clear and precise learning outcomes
793
- - **M**easurable: Can be assessed and observed
794
- - **A**chievable: Realistic within lesson time
795
- - **R**elevant: Aligned with curriculum standards
796
- - **T**ime-bound: Achievable in one lesson period
797
-
798
- ### 🔑 API Configuration:
799
-
800
- **Before using this tool**, you need to set up your Groq API key:
801
-
802
- 1. Get your free API key from: https://console.groq.com/
803
- 2. Set it as an environment variable:
804
- ```bash
805
- export GROQ_API_KEY=your_api_key_here
806
- ```
807
- 3. Or add it to your `.env` file
808
-
809
- The app uses the **openai/gpt-oss-120b** model for high-quality educational content generation.
810
- """)
811
-
812
  gr.Markdown("---")
813
 
814
- # Output section with enhanced styling
815
- gr.HTML('<div class="section-header"><h3>📥 Your Generated Lesson Plan</h3></div>')
816
 
817
  with gr.Row():
818
  with gr.Column(scale=2):
819
  status_output = gr.Textbox(
820
- label="📊 Generation Status",
821
  interactive=False,
822
- lines=12,
823
- placeholder="Status messages will appear here..."
824
  )
825
  with gr.Column(scale=1):
826
  output_file = gr.File(
827
- label="💾 Download File",
828
- file_count="single"
829
  )
830
 
831
  # Event handlers
@@ -845,103 +791,11 @@ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, title="SMART Lesson Plan
845
  ],
846
  outputs=[output_file, status_output]
847
  )
848
-
849
- # Footer with additional information
850
- gr.Markdown("---")
851
-
852
- with gr.Accordion("ℹ️ About & Support", open=False):
853
- gr.Markdown("""
854
- ### 📱 About This Application
855
-
856
- **Version:** 2.1 (Groq AI Edition)
857
- **Developer:** Najaf Ali Sharqi
858
- **Organization:** School Education Department, Gilgit-Baltistan
859
- **AI Model:** Groq openai/gpt-oss-120b
860
- **Speed:** Ultra-fast generation (10-20 seconds)
861
-
862
- ### 🎯 Features:
863
-
864
- - ✅ SMART Learning Outcomes (Bloom's Taxonomy aligned)
865
- - ✅ Comprehensive lesson procedures with timings
866
- - ✅ National Curriculum Framework compliance
867
- - ✅ Bilingual support (English & Urdu)
868
- - ✅ Professional Word document formatting
869
- - ✅ Differentiation strategies
870
- - ✅ Assessment guidelines
871
- - ✅ Home assignments
872
- - ✅ Powered by Groq's ultra-fast AI inference
873
-
874
- ### 🤖 About Groq AI:
875
-
876
- This application uses Groq's **openai/gpt-oss-120b** model, which provides:
877
- - Lightning-fast inference speed
878
- - High-quality educational content
879
- - Reasoning capabilities for better lesson structure
880
- - Support for both English and Urdu languages
881
-
882
- ### 📞 Support & Feedback:
883
-
884
- For technical support, feature requests, or to report issues:
885
- - **Email:** Contact School Education Department
886
- - **Feedback:** Use the feedback option in your district office
887
- - **API Issues:** Check https://console.groq.com/ for API status
888
-
889
- ### 🔒 Privacy & Data:
890
-
891
- - All lesson plans are generated in real-time
892
- - No data is stored on external servers
893
- - Your lesson plans remain confidential
894
- - Files are temporarily created and deleted after download
895
-
896
- ### 📚 Resources:
897
-
898
- - **Groq Console:** https://console.groq.com/
899
- - **Groq Documentation:** https://console.groq.com/docs
900
- - **National Curriculum:** http://www.mofept.gov.pk/
901
- - **Bloom's Taxonomy Guide:** Refer to teacher training materials
902
-
903
- ### 🙏 Acknowledgments:
904
-
905
- This tool was developed to support teachers in Gilgit-Baltistan in creating high-quality,
906
- standards-aligned lesson plans efficiently. Special thanks to:
907
- - All educators who provided feedback during development
908
- - Groq AI for providing powerful, fast AI inference
909
- - School Education Department, Gilgit-Baltistan
910
-
911
- ---
912
-
913
- **© 2024 School Education Department, Gilgit-Baltistan**
914
- *Empowering Teachers, Enriching Learning*
915
- """)
916
-
917
- # Quick reference guide
918
- with gr.Accordion("📋 Quick Reference: Bloom's Taxonomy", open=False):
919
- gr.Markdown("""
920
- ### Understanding Bloom's Taxonomy Levels
921
-
922
- | Level | Action Verbs | Sample SLO |
923
- |-------|-------------|------------|
924
- | **Knowledge** (Remember) | Define, List, Identify, Recall, Name, State | "Students will be able to **identify** the main parts of a plant cell" |
925
- | **Understanding** (Comprehend) | Explain, Describe, Summarize, Interpret, Compare | "Students will be able to **explain** the process of photosynthesis" |
926
- | **Application** (Apply) | Apply, Demonstrate, Solve, Calculate, Use | "Students will be able to **apply** the Pythagorean theorem to solve problems" |
927
- | **Analysis** (Analyze) | Analyze, Differentiate, Examine, Compare | "Students will be able to **analyze** the causes of climate change" |
928
- | **Evaluation** (Evaluate) | Evaluate, Judge, Critique, Justify | "Students will be able to **evaluate** the effectiveness of different solutions" |
929
- | **Creation** (Create) | Create, Design, Develop, Compose | "Students will be able to **design** an experiment to test their hypothesis" |
930
-
931
- ### 💡 Tips:
932
- - Start with lower levels (Knowledge, Understanding) for new topics
933
- - Progress to higher levels (Application, Analysis) as students master basics
934
- - Each lesson should target 2-3 adjacent levels
935
- - Match the cognitive level to student readiness and topic complexity
936
- """)
937
 
938
- # Launch configuration
939
  if __name__ == "__main__":
940
  demo.launch(
941
  server_name="0.0.0.0",
942
  server_port=7860,
943
  share=False,
944
- show_error=True,
945
- max_threads=10,
946
- inbrowser=True
947
  )
 
12
  # Initialize Groq client with error handling
13
  try:
14
  client = Groq()
15
+ print("Groq client initialized successfully")
 
16
  except Exception as e:
17
  print(f"Warning: Groq client initialization failed: {e}")
18
  client = None
 
46
  "Peer Assessment", "Self Assessment", "Portfolio Assessment"
47
  ]
48
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  def update_subjects(grade_range):
50
  """Update subject dropdown based on grade selection"""
51
  if not grade_range:
 
89
  tblBorders.append(border)
90
  tblPr.append(tblBorders)
91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  def generate_lesson_plan(language, grade_range, grade_specific, subject, topic,
93
  school_name, teacher_name, district, date_input,
94
  students, duration, teaching_method, assessment_type,
 
97
  # Validate inputs
98
  validation_errors = validate_inputs(language, grade_range, subject, topic, teacher_name, school_name)
99
  if validation_errors:
100
+ error_msg = "Please fix the following errors:\n" + "\n".join(f"- {e}" for e in validation_errors)
101
  return None, error_msg
102
 
103
  # Check if client is initialized
104
  if client is None:
105
+ return None, "Error: Groq API client not initialized. Please check your API key."
106
 
107
  # Format date
108
  if date_input:
 
118
  if grade_specific:
119
  full_grade = grade_specific
120
  else:
121
+ full_grade = grade_range.split('-')[0]
122
 
123
  # Calculate time allocations
124
  intro_time = int(duration * 0.15)
 
126
  conclusion_time = int(duration * 0.15)
127
  assessment_time = duration - (intro_time + main_time + conclusion_time)
128
 
129
+ # Build prompt based on language
130
+ if language == "English":
131
+ prompt = f"""You are an expert Pakistani educator and curriculum specialist with deep knowledge of the National Curriculum Framework.
132
 
133
+ Create a COMPREHENSIVE SMART LESSON PLAN in English language.
134
 
135
  **LESSON DETAILS:**
136
  - Grade: {full_grade}
 
147
 
148
  **CRITICAL INSTRUCTIONS:**
149
 
150
+ 1. DO NOT repeat the information table - it will be added automatically
151
+ 2. DO NOT use emojis, symbols, or special characters
152
+ 3. Write ONLY these THREE sections in this exact order:
153
+ - SMART STUDENT LEARNING OUTCOMES (SLOs)
154
+ - CONTENT KNOWLEDGE
155
+ - HOME ASSIGNMENT
156
+
157
+ **SECTION 1: SMART STUDENT LEARNING OUTCOMES (SLOs)**
158
+
159
+ Write EXACTLY THREE SLOs following Bloom's Taxonomy:
160
+
161
+ SLO 1 (Knowledge Level): Use verbs like Define, List, Identify, Recall, State, Name
162
+ SLO 2 (Understanding Level): Use verbs like Explain, Describe, Summarize, Interpret, Compare
163
+ SLO 3 (Application Level): Use verbs like Apply, Demonstrate, Solve, Calculate, Use
164
+
165
+ Format: "By the end of this lesson, students will be able to [verb] [specific content] [criteria]."
166
+
167
+ Make each SLO:
168
+ - Specific and measurable
169
+ - Achievable in {duration} minutes
170
+ - Aligned with curriculum standards
171
+ - Observable and assessable
172
+
173
+ **SECTION 2: CONTENT KNOWLEDGE**
174
+
175
+ Provide comprehensive coverage including:
176
+
177
+ 1. Main concepts and key ideas for this topic
178
+ 2. Important definitions and terminology
179
+ 3. Essential facts students must learn
180
+ 4. Prior knowledge students should have
181
+ 5. Common misconceptions and how to correct them
182
+ 6. Real-world connections relevant to Gilgit-Baltistan
183
+ 7. Detailed lesson procedure:
184
+ - Introduction activities ({intro_time} minutes): engaging hook, activate prior knowledge, state objectives
185
+ - Main teaching activities ({main_time} minutes): step-by-step explanation using {teaching_method}, examples, student practice tasks
186
+ - Assessment activities ({assessment_time} minutes): {assessment_type}, questions for each SLO, feedback strategies
187
+ - Conclusion ({conclusion_time} minutes): summary, reflection, connect to next lesson
188
+ {"8. Teaching resources and materials needed" if include_resources else ""}
189
+ {"9. Differentiation strategies for advanced and struggling learners" if include_differentiation else ""}
190
+
191
+ Write in clear paragraphs with natural flow. Be detailed and practical.
192
+
193
+ **SECTION 3: HOME ASSIGNMENT**
194
+
195
+ Create assignment that:
196
+ - Reinforces all three SLOs
197
+ - Appropriate for {full_grade} level
198
+ - Can be completed in 20-30 minutes
199
+ - Has clear instructions
200
+ - Includes 3-5 specific questions or tasks
201
+ - Provides marking criteria
202
+
203
+ **FORMATTING:**
204
+ - Use clear professional language
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
205
  - Write in complete sentences and paragraphs
206
+ - NO emojis, NO symbols, NO special characters
207
+ - Only use the three section headings listed above
208
+ - Be specific and practical
 
 
 
209
 
210
+ Generate the lesson plan now:"""
211
+
212
+ else: # Urdu
213
+ prompt = f"""آپ ایک ماہر پاکستانی استاد اور نصاب کے ماہر ہیں۔
214
 
215
+ اردو زبان میں ایک جامع اسمارٹ سبق منصوبہ تیار کریں۔
216
+
217
+ **سبق کی تفصیلات:**
218
+ - درجہ: {full_grade}
219
+ - مضمون: {subject}
220
+ - موضوع: {topic}
221
+ - اسکول: {school_name}
222
+ - استاد: {teacher_name}
223
+ - ضلع: {district}، گلگت بلتستان
224
+ - تاریخ: {formatted_date}
225
+ - طلبہ کی تعداد: {students}
226
+ - دورانیہ: {duration} منٹ
227
+ - تدریسی طریقہ: {teaching_method}
228
+ - تشخیصی طریقہ: {assessment_type}
229
+
230
+ **اہم ہدایات:**
231
+
232
+ 1. معلوماتی جدول دوبارہ نہ لکھیں - یہ خودکار شامل ہوگا
233
+ 2. کوئی خاص علامات یا انگریزی الفاظ استعمال نہ کریں
234
+ 3. صرف یہ تین حصے اسی ترتیب میں لکھیں:
235
+ - اسمارٹ طلبہ سیکھنے کے نتائج
236
+ - علمی مواد
237
+ - گھر کی تفویض
238
+
239
+ **حصہ اول: اسمارٹ طلبہ سیکھنے کے نتائج**
240
+
241
+ بلوم ٹیکسانومی کے مطابق بالکل تین نتائج لکھیں:
242
+
243
+ نتیجہ ١ (علم کی سطح): فعل استعمال کریں جیسے تعریف کریں، فہرست بنائیں، شناخت کریں
244
+ نتیجہ ٢ (فہم کی سطح): فعل استعمال کریں جیسے وضاحت کریں، بیان کریں، خلاصہ کریں
245
+ نتیجہ ٣ (اطلاق کی سطح): فعل استعمال کریں جیسے استعمال کریں، حل کریں، ظاہر کریں
246
+
247
+ ہر نتیجہ یوں لکھیں: "اس سبق کے اختتام تک طلبہ [فعل] [مخصوص مواد] کر سکیں گے۔"
248
+
249
+ ہر نتیجہ:
250
+ - مخصوص اور قابل پیمائش ہو
251
+ - {duration} منٹ میں حاصل کیا جا سکے
252
+ - نصاب کے معیار سے مطابقت رکھتا ہو
253
+
254
+ **حصہ دوم: علمی مواد**
255
+
256
+ جامع تفصیل فراہم کریں:
257
+
258
+ ١۔ اس موضوع کے بنیادی تصورات اور اہم نکات
259
+ ٢۔ اہم تعریفات اور اصطلاحات
260
+ ٣۔ لازمی حقائق جو طلبہ کو سیکھنے چاہیں
261
+ ٤۔ پیشگی علم جو طلبہ کو ہونا چاہیے
262
+ ٥۔ عام غلط فہمیاں اور ان کی اصلاح
263
+ ٦۔ گلگت بلتستان کے تناظر میں حقیقی زندگی سے تعلق
264
+ ٧۔ تفصیلی سبق کا طریقہ کار:
265
+ - تعارفی سرگرمیاں ({intro_time} منٹ): دلچسپ آغاز، سابقہ علم کو فعال کرنا، مقاصد بیان کرنا
266
+ - بنیادی تدریسی سرگرمیاں ({main_time} منٹ): {teaching_method} استعمال کرتے ہوئے قدم بہ قدم وضاحت، مثالیں، طلبہ کی مشق
267
+ - تشخیصی سرگرمیاں ({assessment_time} منٹ): {assessment_type}، ہر نتیجے کے لیے سوالات، رائے کی حکمت عملی
268
+ - اختتام ({conclusion_time} منٹ): خلاصہ، غور و فکر، اگلے سبق سے ربط
269
+ {"٨۔ تدریسی وسائل اور مواد" if include_resources else ""}
270
+ {"٩۔ مختلف سطح کے طلبہ کے لیے حکمت عملی" if include_differentiation else ""}
271
+
272
+ واضح پیراگراف میں قدرتی انداز سے لکھیں۔ تفصیلی اور عملی ہو۔
273
+
274
+ **حصہ سوم: گھر کی تفویض**
275
+
276
+ ایسی تفویض بنائیں جو:
277
+ - تینوں نتائج کو مضبوط کرے
278
+ - {full_grade} کی سطح کے مطابق ہو
279
+ - ٢٠-٣٠ منٹ میں مکمل ہو سکے
280
+ - واضح ہدایات ہوں
281
+ - ٣-٥ مخصوص سوالات یا کام شامل ہوں
282
+ - نمبر دینے کا معیار فراہم کریں
283
+
284
+ **فارمیٹنگ:**
285
+ - واضح پیشہ ورانہ زبان استعمال کریں
286
+ - مکمل جملوں اور پیراگراف میں لکھیں
287
+ - کوئی خاص علامات یا انگریزی الفاظ نہ ہوں
288
+ - صرف اوپر دیے گئے تین حصے استعمال کریں
289
+ - تمام مواد اردو حروف میں لکھیں
290
+
291
+ اب سبق منصوبہ تیار کریں:"""
292
 
293
  try:
294
+ # Generate content using Groq API
295
+ print("Generating lesson plan with Groq API...")
296
 
297
  completion = client.chat.completions.create(
298
  model="openai/gpt-oss-120b",
299
  messages=[
300
  {
301
  "role": "system",
302
+ "content": "You are an expert Pakistani educator. Generate comprehensive lesson plans following exact formatting requirements. Do not use emojis or special characters."
303
  },
304
  {
305
  "role": "user",
306
  "content": prompt
307
  }
308
  ],
309
+ temperature=0.7,
310
  max_completion_tokens=8192,
311
  top_p=0.95,
312
+ reasoning_effort="high",
313
  stream=True,
314
  stop=None
315
  )
316
 
317
+ # Collect streamed response
318
  lesson_text = ""
319
  for chunk in completion:
320
  if chunk.choices[0].delta.content:
321
  lesson_text += chunk.choices[0].delta.content
322
 
323
  lesson_text = lesson_text.strip()
324
+ print(f"Generated {len(lesson_text)} characters")
325
 
326
+ # Clean up any accidental prefixes
327
+ lesson_text = re.sub(r'^.*?(SMART|SLO|اسمارٹ)', r'\1', lesson_text, flags=re.DOTALL | re.IGNORECASE)
328
 
329
  # Create Word document
330
  doc = Document()
 
338
  section.right_margin = Inches(0.75)
339
 
340
  if language == "English":
341
+ # Header
342
+ header = doc.add_paragraph()
343
+ run = header.add_run("Government of Gilgit-Baltistan\n")
344
+ run.bold = True
345
+ run.font.size = Pt(14)
346
+ header.alignment = WD_ALIGN_PARAGRAPH.CENTER
347
+
348
+ run2 = header.add_run("School Education Department")
349
+ run2.bold = True
350
+ run2.font.size = Pt(13)
351
+ header.alignment = WD_ALIGN_PARAGRAPH.CENTER
352
+
353
+ # Title
354
+ title = doc.add_paragraph()
355
+ run = title.add_run("SMART LESSON PLAN")
356
+ run.bold = True
357
+ run.font.size = Pt(14)
358
+ run.underline = True
359
+ title.alignment = WD_ALIGN_PARAGRAPH.CENTER
360
+ title.space_after = Pt(12)
361
 
362
+ # Information table
363
  table = doc.add_table(rows=6, cols=4)
364
  add_table_border(table)
365
 
 
366
  def style_cell(cell, text, bold=False, bg_color=None):
367
  cell.text = text
368
  if bold:
 
375
  shading_elm.set(qn('w:fill'), bg_color)
376
  cell._element.get_or_add_tcPr().append(shading_elm)
377
 
378
+ # Fill table
379
  cells = table.rows[0].cells
380
  style_cell(cells[0], "Grade", bold=True, bg_color="E7E6E6")
381
  style_cell(cells[1], full_grade)
 
411
  merged_cell = cells[1].merge(cells[3])
412
  style_cell(merged_cell, assessment_type)
413
 
414
+ doc.add_paragraph()
415
 
416
+ # Process lesson content
417
  lines = lesson_text.split("\n")
418
 
419
  for line in lines:
 
421
  if not line_stripped:
422
  continue
423
 
424
+ # Detect only the three allowed headings
425
  is_main_heading = any(keyword in line_stripped.upper() for keyword in
426
  ["SMART STUDENT LEARNING OUTCOMES", "CONTENT KNOWLEDGE",
427
+ "HOME ASSIGNMENT"])
 
 
 
 
 
 
 
 
 
428
 
429
  # Detect SLOs
430
  is_slo = line_stripped.upper().startswith("SLO") or re.match(r'^(SLO\s*[1-3]|BY THE END)', line_stripped.upper())
 
436
  if is_main_heading:
437
  para.runs[0].bold = True
438
  para.runs[0].font.size = Pt(12)
 
439
  para.paragraph_format.space_before = Pt(12)
440
  para.paragraph_format.space_after = Pt(8)
 
 
 
 
 
441
  elif is_slo:
442
  para.runs[0].bold = True
 
443
  para.paragraph_format.left_indent = Inches(0.25)
444
 
445
+ # Separator
446
  doc.add_paragraph()
447
+ separator = doc.add_paragraph("." * 100)
448
  separator.alignment = WD_ALIGN_PARAGRAPH.CENTER
449
+ separator.paragraph_format.space_before = Pt(12)
450
 
451
+ # Save file
 
 
 
 
 
 
 
 
 
 
 
 
452
  safe_topic = re.sub(r'[^\w\s-]', '', topic).strip()[:30]
453
  file_path = f"/tmp/LP_{subject}_{safe_topic}_{full_grade}_{formatted_date}.docx"
454
  doc.save(file_path)
455
 
456
+ status_msg = f"""Lesson Plan Generated Successfully!
457
 
458
+ File Details:
459
  - Subject: {subject}
460
  - Grade: {full_grade}
461
  - Topic: {topic}
462
  - Duration: {duration} minutes
463
  - Date: {formatted_date}
464
 
465
+ File Name: {os.path.basename(file_path)}
466
 
467
+ The lesson plan includes:
468
+ - Three SMART Student Learning Outcomes
469
+ - Comprehensive Content Knowledge
470
+ - Home Assignment
 
471
 
472
+ Download the file and review it for your classroom use."""
 
 
 
 
 
 
 
473
 
474
+ else: # Urdu
475
  # Create Urdu document
476
  doc = Document()
477
 
478
+ # Header in Urdu
479
  header = doc.add_paragraph()
480
  run = header.add_run("حکومت گلگت بلتستان\nمحکمہ تعلیم")
481
  run.bold = True
482
+ run.font.size = Pt(14)
 
483
  header.alignment = WD_ALIGN_PARAGRAPH.CENTER
484
  header.paragraph_format.right_to_left = True
485
 
486
+ # Title
487
+ title = doc.add_paragraph()
488
+ run = title.add_run("اسمارٹ سبق کا منصوبہ")
489
  run.bold = True
490
  run.font.size = Pt(14)
491
  run.underline = True
492
+ title.alignment = WD_ALIGN_PARAGRAPH.CENTER
493
+ title.paragraph_format.right_to_left = True
494
+ title.space_after = Pt(12)
495
+
496
+ # Information table (Urdu)
497
+ table = doc.add_table(rows=6, cols=4)
498
+ add_table_border(table)
499
+
500
+ def style_cell_urdu(cell, text, bold=False, bg_color=None):
501
+ cell.text = text
502
+ for paragraph in cell.paragraphs:
503
+ paragraph.alignment = WD_ALIGN_PARAGRAPH.RIGHT
504
+ paragraph.paragraph_format.right_to_left = True
505
+ if bold:
506
+ for run in paragraph.runs:
507
+ run.bold = True
508
+ run.font.size = Pt(10)
509
+ if bg_color:
510
+ shading_elm = OxmlElement('w:shd')
511
+ shading_elm.set(qn('w:fill'), bg_color)
512
+ cell._element.get_or_add_tcPr().append(shading_elm)
513
+
514
+ # Fill table (Urdu)
515
+ cells = table.rows[0].cells
516
+ style_cell_urdu(cells[3], "درجہ", bold=True, bg_color="E7E6E6")
517
+ style_cell_urdu(cells[2], full_grade)
518
+ style_cell_urdu(cells[1], "مضمون", bold=True, bg_color="E7E6E6")
519
+ style_cell_urdu(cells[0], subject)
520
+
521
+ cells = table.rows[1].cells
522
+ style_cell_urdu(cells[3], "موضوع", bold=True, bg_color="E7E6E6")
523
+ style_cell_urdu(cells[2], topic)
524
+ style_cell_urdu(cells[1], "دورانیہ", bold=True, bg_color="E7E6E6")
525
+ style_cell_urdu(cells[0], f"{duration} منٹ")
526
+
527
+ cells = table.rows[2].cells
528
+ style_cell_urdu(cells[3], "استاد", bold=True, bg_color="E7E6E6")
529
+ style_cell_urdu(cells[2], teacher_name)
530
+ style_cell_urdu(cells[1], "تاریخ", bold=True, bg_color="E7E6E6")
531
+ style_cell_urdu(cells[0], formatted_date)
532
+
533
+ cells = table.rows[3].cells
534
+ style_cell_urdu(cells[3], "اسکول", bold=True, bg_color="E7E6E6")
535
+ style_cell_urdu(cells[2], school_name)
536
+ style_cell_urdu(cells[1], "ضلع", bold=True, bg_color="E7E6E6")
537
+ style_cell_urdu(cells[0], f"{district}، گلگت بلتستان")
538
+
539
+ cells = table.rows[4].cells
540
+ style_cell_urdu(cells[3], "طلبہ کی تعداد", bold=True, bg_color="E7E6E6")
541
+ style_cell_urdu(cells[2], str(int(students)))
542
+ style_cell_urdu(cells[1], "تدریسی طریقہ", bold=True, bg_color="E7E6E6")
543
+ style_cell_urdu(cells[0], teaching_method)
544
+
545
+ cells = table.rows[5].cells
546
+ style_cell_urdu(cells[3], "تشخیصی طریقہ", bold=True, bg_color="E7E6E6")
547
+ merged_cell = cells[0].merge(cells[2])
548
+ style_cell_urdu(merged_cell, assessment_type)
549
+
550
+ doc.add_paragraph()
551
 
552
  # Add Urdu lesson content
553
  for line in lesson_text.split("\n"):
 
557
  para.paragraph_format.right_to_left = True
558
  para.paragraph_format.space_after = Pt(6)
559
  para.paragraph_format.line_spacing = 1.5
560
+
561
+ # Make headings bold
562
+ if any(keyword in line.strip() for keyword in
563
+ ["اسمارٹ طلبہ سیکھنے کے نتائج", "علمی مواد", "گھر کی تفویض"]):
564
+ for run in para.runs:
565
+ run.bold = True
566
+ run.font.size = Pt(12)
567
 
568
+ # Separator
569
+ doc.add_paragraph()
570
+ separator = doc.add_paragraph("۔" * 100)
571
+ separator.alignment = WD_ALIGN_PARAGRAPH.CENTER
572
+ separator.paragraph_format.right_to_left = True
573
+
574
+ # Save file
575
  safe_topic = re.sub(r'[^\w\s-]', '', topic).strip()[:30]
576
  file_path = f"/tmp/LP_Urdu_{safe_topic}_{formatted_date}.docx"
577
  doc.save(file_path)
578
 
579
+ status_msg = f"""سبق کا منصوبہ تیار ہو گیا!
580
 
581
+ تفصیلات:
582
  - مضمون: {subject}
583
  - درجہ: {full_grade}
584
  - موضوع: {topic}
585
 
586
+ فائل: {os.path.basename(file_path)}
587
 
588
+ سبق منصوبہ میں شامل ہے:
589
+ - تین اسمارٹ سیکھنے کے نتائج
590
+ - جامع علمی مواد
591
+ - گھر کی تفویض"""
592
 
593
  return file_path, status_msg
594
 
595
  except Exception as e:
596
+ error_details = f"""Error Generating Lesson Plan
 
 
 
597
 
598
+ Error Type: {type(e).__name__}
599
+ Details: {str(e)}
 
 
 
 
600
 
601
+ Troubleshooting:
602
+ 1. Check internet connection
603
+ 2. Verify Groq API key (GROQ_API_KEY)
604
+ 3. Check API credits at console.groq.com
605
+ 4. Try simpler topic
606
 
607
+ If problem persists, contact support."""
608
 
609
  return None, error_details
610
 
611
 
612
+ # Gradio Interface
613
  custom_css = """
614
  .gradio-container {
615
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif !important;
 
628
  margin: 1.5rem 0 1rem 0;
629
  border-radius: 5px;
630
  }
 
 
 
 
 
 
 
631
  """
632
 
633
+ with gr.Blocks(theme=gr.themes.Soft(), css=custom_css, title="SMART Lesson Plan Generator") as demo:
634
 
635
+ # Header
636
  with gr.Row():
637
  gr.HTML("""
638
  <div class="main-header">
639
+ <h1 style="margin:0; font-size: 2.5rem;">SMART Lesson Plan Generator</h1>
640
  <p style="margin: 0.5rem 0 0 0; font-size: 1.1rem; opacity: 0.9;">
641
  Professional Lesson Planning Tool for Gilgit-Baltistan Schools
642
  </p>
643
  <p style="margin: 0.3rem 0 0 0; font-size: 0.9rem; opacity: 0.8;">
644
+ Powered by Groq AI | Developed by Najaf Ali Sharqi
645
  </p>
646
  </div>
647
  """)
648
 
649
+ # Main form
650
+ gr.HTML('<div class="section-header"><h3>Basic Information</h3></div>')
 
 
 
 
 
 
 
 
 
 
 
651
 
652
  with gr.Row():
653
  language = gr.Dropdown(
654
  choices=["English", "Urdu"],
655
+ label="Language",
656
  value="English",
 
657
  interactive=True
658
  )
659
  grade_range = gr.Dropdown(
660
  choices=["Grade 1-5", "Grade 6-8", "Grade 9-10", "Grade 11-12"],
661
+ label="Grade Range",
 
662
  interactive=True
663
  )
664
  grade_specific = gr.Dropdown(
665
  choices=[f"Grade {i}" for i in range(1, 13)],
666
+ label="Specific Grade (Optional)",
 
667
  interactive=True
668
  )
669
 
670
  with gr.Row():
671
  subject = gr.Dropdown(
672
  choices=[],
673
+ label="Subject",
 
674
  interactive=True
675
  )
676
  topic = gr.Textbox(
677
+ label="Lesson Topic",
678
+ placeholder="e.g., Photosynthesis, Fractions, Parts of Speech",
 
679
  lines=1
680
  )
681
 
682
+ gr.HTML('<div class="section-header"><h3>School & Teacher Details</h3></div>')
683
 
684
  with gr.Row():
685
  school_name = gr.Textbox(
686
+ label="School Name",
687
  placeholder="e.g., Government High School Gilgit",
 
688
  lines=1
689
  )
690
  teacher_name = gr.Textbox(
691
+ label="Teacher Name",
692
  placeholder="e.g., Muhammad Ali Khan",
 
693
  lines=1
694
  )
695
  district = gr.Dropdown(
696
  choices=DISTRICTS_GB,
697
+ label="District",
698
  value="Gilgit",
 
699
  interactive=True
700
  )
701
 
702
+ gr.HTML('<div class="section-header"><h3>Class Details</h3></div>')
703
 
704
  with gr.Row():
705
  date_input = gr.Textbox(
706
+ label="Date",
707
  value=datetime.now().strftime("%Y-%m-%d"),
708
+ placeholder="YYYY-MM-DD"
 
709
  )
710
  students = gr.Number(
711
+ label="Number of Students",
712
  value=35,
713
  minimum=1,
714
  maximum=100,
715
+ step=1
 
716
  )
717
  duration = gr.Dropdown(
718
  choices=[35, 40, 45, 50, 60, 70, 80, 90],
719
+ label="Duration (minutes)",
720
  value=40,
 
721
  interactive=True
722
  )
723
 
724
+ gr.HTML('<div class="section-header"><h3>Teaching Methods</h3></div>')
725
 
726
  with gr.Row():
727
  teaching_method = gr.Dropdown(
728
  choices=TEACHING_METHODS,
729
+ label="Teaching Method",
730
  value="Lecture Method",
 
731
  interactive=True
732
  )
733
  assessment_type = gr.Dropdown(
734
  choices=ASSESSMENT_TYPES,
735
+ label="Assessment Method",
736
  value="Formative Assessment",
 
737
  interactive=True
738
  )
739
 
740
+ gr.HTML('<div class="section-header"><h3>Additional Options</h3></div>')
741
 
742
  with gr.Row():
743
+ include_resources = gr.Checkbox(
744
+ label="Include Teaching Resources",
745
+ value=True
746
+ )
747
+ include_differentiation = gr.Checkbox(
748
+ label="Include Differentiation Strategies",
749
+ value=True
750
+ )
 
 
 
 
751
 
752
  gr.Markdown("---")
753
 
 
754
  generate_btn = gr.Button(
755
+ "Generate Lesson Plan",
756
  variant="primary",
757
+ size="lg"
 
758
  )
759
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
760
  gr.Markdown("---")
761
 
762
+ gr.HTML('<div class="section-header"><h3>Generated Lesson Plan</h3></div>')
 
763
 
764
  with gr.Row():
765
  with gr.Column(scale=2):
766
  status_output = gr.Textbox(
767
+ label="Status",
768
  interactive=False,
769
+ lines=10,
770
+ placeholder="Generation status will appear here..."
771
  )
772
  with gr.Column(scale=1):
773
  output_file = gr.File(
774
+ label="Download File"
 
775
  )
776
 
777
  # Event handlers
 
791
  ],
792
  outputs=[output_file, status_output]
793
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
794
 
 
795
  if __name__ == "__main__":
796
  demo.launch(
797
  server_name="0.0.0.0",
798
  server_port=7860,
799
  share=False,
800
+ show_error=True
 
 
801
  )