Spaces:
Sleeping
Sleeping
File size: 22,407 Bytes
6cff14b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 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 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 | """
Content generators module for BrightMind AI
Handles lesson plan and quiz generation functionality
"""
from config import HF_TOKEN, PROGRESS_HTML, COMPLETION_HTML, FALLBACK_HTML
from ai_services import call_hugging_face_api_content
from utils import typewriter_effect, process_content_with_images, apply_content_styling
def generate_lesson_plan_with_progress(topic, subject, grade_level, duration, difficulty="intermediate"):
"""Generate a lesson plan with progress updates"""
# Show progress bar
yield PROGRESS_HTML, ""
print(f"π Starting lesson plan generation for: {topic}")
print(f"π Subject: {subject}, Grade: {grade_level}, Duration: {duration}min")
# Try Hugging Face API first if token is available
if HF_TOKEN:
print("π€ Token found! Attempting Hugging Face API call...")
try:
prompt = f"""Create a comprehensive lesson plan for:
Topic: {topic}
Subject: {subject}
Grade Level: {grade_level}
Duration: {duration} minutes
Difficulty: {difficulty}
Include:
1. Learning objectives
2. Activities with time allocations
3. Materials needed
4. Assessment methods
5. Differentiation strategies
6. Educational standards
7. Real-world connections
8. Extension activities
Make it practical, engaging, and ready for classroom use."""
result = call_hugging_face_api_content(prompt)
if result:
print("β
Successfully generated with Hugging Face API")
# Show completion and return result
yield COMPLETION_HTML, result
else:
print("β API call returned no content, falling back to algorithms")
raise Exception("No content returned from API")
except Exception as e:
print(f"β Hugging Face API failed: {e}")
print("π Falling back to educational algorithms...")
# Show fallback progress
yield FALLBACK_HTML, ""
result = generate_with_algorithms(topic, subject, grade_level, duration, difficulty)
print("β
Generated with educational algorithms")
# Show completion
yield COMPLETION_HTML, result
else:
print("β οΈ No Hugging Face token found, using educational algorithms...")
# Show progress for algorithms
yield FALLBACK_HTML, ""
result = generate_with_algorithms(topic, subject, grade_level, duration, difficulty)
print("β
Generated with educational algorithms")
# Show completion
yield COMPLETION_HTML, result
def generate_lesson_plan(topic, subject, grade_level, duration, difficulty="intermediate"):
"""Generate a lesson plan using Hugging Face API or fallback algorithms"""
print(f"π Starting lesson plan generation for: {topic}")
print(f"π Subject: {subject}, Grade: {grade_level}, Duration: {duration}min")
# Try Hugging Face API first if token is available
if HF_TOKEN:
print("π€ Token found! Attempting Hugging Face API call...")
try:
result = generate_with_hugging_face(topic, subject, grade_level, duration, difficulty)
print("β
Successfully generated with Hugging Face API")
return result
except Exception as e:
print(f"β Hugging Face API failed: {e}")
print("π Falling back to educational algorithms...")
else:
print("β οΈ No Hugging Face token found, using educational algorithms...")
# Fallback to educational algorithms
result = generate_with_algorithms(topic, subject, grade_level, duration, difficulty)
print("β
Generated with educational algorithms")
return result
def generate_with_hugging_face(topic, subject, grade_level, duration, difficulty):
"""Generate lesson plan using Hugging Face API"""
prompt = f"""Create a comprehensive lesson plan for:
Topic: {topic}
Subject: {subject}
Grade Level: {grade_level}
Duration: {duration} minutes
Difficulty: {difficulty}
Include:
1. Learning objectives
2. Activities with time allocations
3. Materials needed
4. Assessment methods
5. Differentiation strategies
6. Educational standards
7. Real-world connections
8. Extension activities
Make it practical, engaging, and ready for classroom use."""
result = call_hugging_face_api_content(prompt)
if result:
return format_lesson_plan(result, topic, subject, grade_level, duration, True)
else:
raise Exception("No content returned from API")
def generate_with_algorithms(topic, subject, grade_level, duration, difficulty):
"""Generate lesson plan using educational algorithms"""
# Generate lesson plan components
objectives = generate_objectives(topic, grade_level)
activities = generate_activities(topic, duration, grade_level)
materials = generate_materials(subject, grade_level)
assessment = generate_assessment(grade_level)
differentiation = generate_differentiation()
# Create structured lesson plan
lesson_plan = {
"topic": topic,
"subject": subject,
"grade_level": grade_level,
"duration": duration,
"difficulty": difficulty,
"objectives": objectives,
"activities": activities,
"materials": materials,
"assessment": assessment,
"differentiation": differentiation
}
return format_lesson_plan_from_dict(lesson_plan)
def generate_objectives(topic, grade):
"""Generate learning objectives for a topic and grade level"""
objectives = [
f"Students will understand the key concepts of {topic}",
f"Students will be able to explain {topic} in their own words",
f"Students will apply knowledge of {topic} to solve problems"
]
if grade in ["6th", "7th", "8th"]:
objectives.append(f"Students will analyze the relationship between {topic} and real-world applications")
elif grade in ["9th", "10th", "11th", "12th"]:
objectives.append(f"Students will evaluate different perspectives on {topic}")
objectives.append(f"Students will create original work demonstrating understanding of {topic}")
return objectives
def generate_activities(topic, duration, grade):
"""Generate activities for a lesson plan"""
activities = []
# Opening activity (10% of duration)
opening_time = max(5, duration // 10)
activities.append({
"name": f"Introduction to {topic}",
"duration": f"{opening_time} minutes",
"description": f"Engage students with a thought-provoking question about {topic}"
})
# Main activities (70% of duration)
main_time = int(duration * 0.7)
if main_time > 20:
activities.append({
"name": f"Explore {topic}",
"duration": f"{main_time // 2} minutes",
"description": f"Hands-on exploration of {topic} concepts"
})
activities.append({
"name": f"Practice with {topic}",
"duration": f"{main_time - main_time // 2} minutes",
"description": f"Guided practice and application of {topic}"
})
else:
activities.append({
"name": f"Learn about {topic}",
"duration": f"{main_time} minutes",
"description": f"Interactive learning about {topic}"
})
# Closing activity (20% of duration)
closing_time = max(5, duration - opening_time - main_time)
activities.append({
"name": f"Reflect on {topic}",
"duration": f"{closing_time} minutes",
"description": f"Students share what they learned about {topic}"
})
return activities
def generate_materials(subject, grade):
"""Generate materials list for a lesson"""
base_materials = [
"Whiteboard and markers",
"Student notebooks",
"Pencils and erasers"
]
if subject.lower() in ["science", "biology", "chemistry", "physics"]:
base_materials.extend([
"Safety goggles",
"Lab materials (as needed)",
"Scientific calculator"
])
elif subject.lower() in ["math", "mathematics", "algebra", "geometry"]:
base_materials.extend([
"Graph paper",
"Ruler and compass",
"Calculator"
])
elif subject.lower() in ["english", "language arts", "literature"]:
base_materials.extend([
"Texts or reading materials",
"Dictionary",
"Highlighters"
])
return base_materials
def generate_assessment(grade):
"""Generate assessment methods for a lesson"""
assessments = [
"Exit ticket with key questions",
"Class participation and discussion",
"Quick quiz on main concepts"
]
if grade in ["9th", "10th", "11th", "12th"]:
assessments.append("Short written reflection")
assessments.append("Peer review activity")
return assessments
def generate_differentiation():
"""Generate differentiation strategies"""
return [
"Provide visual aids for visual learners",
"Offer hands-on activities for kinesthetic learners",
"Use audio explanations for auditory learners",
"Provide additional support for struggling students",
"Offer extension activities for advanced students"
]
def format_lesson_plan(content, topic, subject, grade_level, duration, ai_generated):
"""Format lesson plan content with proper styling"""
# Process content with images and math
processed_content = process_content_with_images(content, topic, "lesson plan")
# Apply content styling
styled_content = apply_content_styling(processed_content, "lesson plan")
# Add header information
header = f"""# π Lesson Plan: {topic}
**Subject:** {subject}
**Grade Level:** {grade_level}
**Duration:** {duration} minutes
**Generated by:** {'AI Assistant' if ai_generated else 'Educational Algorithms'}
---
"""
return header + styled_content
def format_lesson_plan_from_dict(lesson_plan):
"""Format lesson plan from dictionary structure"""
content = f"""# π Lesson Plan: {lesson_plan['topic']}
**Subject:** {lesson_plan['subject']}
**Grade Level:** {lesson_plan['grade_level']}
**Duration:** {lesson_plan['duration']} minutes
**Difficulty:** {lesson_plan['difficulty']}
**Generated by:** Educational Algorithms
---
## π― Learning Objectives
"""
for i, objective in enumerate(lesson_plan['objectives'], 1):
content += f"{i}. {objective}\n"
content += "\n## π Activities\n\n"
for activity in lesson_plan['activities']:
content += f"### {activity['name']} ({activity['duration']})\n"
content += f"{activity['description']}\n\n"
content += "## π¦ Materials Needed\n\n"
for material in lesson_plan['materials']:
content += f"- {material}\n"
content += "\n## π Assessment Methods\n\n"
for assessment in lesson_plan['assessment']:
content += f"- {assessment}\n"
content += "\n## π¨ Differentiation Strategies\n\n"
for strategy in lesson_plan['differentiation']:
content += f"- {strategy}\n"
return content
def generate_quiz_with_progress(topic, subject, grade_level, question_count, question_types):
"""Generate quiz with progress updates"""
# Show progress bar
yield PROGRESS_HTML, ""
print(f"π Starting quiz generation for: {topic}")
print(f"π Subject: {subject}, Grade: {grade_level}, Questions: {question_count}")
# Try Hugging Face API first if token is available
if HF_TOKEN:
print("π€ Token found! Attempting Hugging Face API call...")
try:
result = generate_quiz_with_hugging_face(topic, subject, grade_level, question_count, question_types)
print("β
Successfully generated with Hugging Face API")
# Show completion and return result
yield COMPLETION_HTML, result
except Exception as e:
print(f"β Hugging Face API failed: {e}")
print("π Falling back to educational algorithms...")
# Show fallback progress
yield FALLBACK_HTML, ""
result = generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types)
print("β
Generated with educational algorithms")
# Show completion
yield COMPLETION_HTML, result
else:
print("β οΈ No Hugging Face token found, using educational algorithms...")
# Show progress for algorithms
yield FALLBACK_HTML, ""
result = generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types)
print("β
Generated with educational algorithms")
# Show completion
yield COMPLETION_HTML, result
def generate_quiz(topic, subject, grade_level, question_count, question_types):
"""Generate quiz using Hugging Face API or fallback algorithms"""
print(f"π Starting quiz generation for: {topic}")
print(f"π Subject: {subject}, Grade: {grade_level}, Questions: {question_count}")
# Try Hugging Face API first if token is available
if HF_TOKEN:
print("π€ Token found! Attempting Hugging Face API call...")
try:
result = generate_quiz_with_hugging_face(topic, subject, grade_level, question_count, question_types)
print("β
Successfully generated with Hugging Face API")
return result
except Exception as e:
print(f"β Hugging Face API failed: {e}")
print("π Falling back to educational algorithms...")
else:
print("β οΈ No Hugging Face token found, using educational algorithms...")
# Fallback to educational algorithms
result = generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types)
print("β
Generated with educational algorithms")
return result
def generate_quiz_with_hugging_face(topic, subject, grade_level, question_count, question_types):
"""Generate quiz using Hugging Face API"""
prompt = f"""Create a {question_count}-question quiz about {topic} for {grade_level} grade {subject} students.
Question types to include: {', '.join(question_types)}
Make the questions:
- Age-appropriate for {grade_level} grade
- Clear and unambiguous
- Cover different aspects of {topic}
- Include a mix of difficulty levels
- Provide clear answer choices for multiple choice questions
Format each question with:
1. Question number
2. Question text
3. Answer choices (for multiple choice)
4. Correct answer
5. Brief explanation
Topic: {topic}
Subject: {subject}
Grade: {grade_level}
Number of questions: {question_count}"""
result = call_hugging_face_api_content(prompt)
if result:
return format_quiz(result, topic, subject, grade_level, question_count, True)
else:
raise Exception("No content returned from API")
def generate_quiz_with_algorithms(topic, subject, grade_level, question_count, question_types):
"""Generate quiz using educational algorithms"""
questions = []
for i in range(question_count):
# Select question type (cycle through available types)
question_type = question_types[i % len(question_types)]
question = generate_question_by_type(question_type, topic, subject, grade_level, i + 1)
questions.append(question)
# Create quiz structure
quiz = {
"topic": topic,
"subject": subject,
"grade_level": grade_level,
"question_count": question_count,
"questions": questions
}
return format_quiz_from_dict(quiz)
def generate_question_by_type(question_type, topic, subject, grade, question_number):
"""Generate a question of specific type"""
if question_type == "Multiple Choice":
return generate_multiple_choice_question(topic, subject, grade, question_number)
elif question_type == "True/False":
return generate_true_false_question(topic, subject, grade, question_number)
elif question_type == "Short Answer":
return generate_short_answer_question(topic, subject, grade, question_number)
elif question_type == "Fill in the Blank":
return generate_fill_in_blank_question(topic, subject, grade, question_number)
else:
return generate_multiple_choice_question(topic, subject, grade, question_number)
def generate_multiple_choice_question(topic, subject, grade, question_number):
"""Generate a multiple choice question"""
questions = [
{
"question": f"What is the main concept of {topic}?",
"options": [
f"The primary idea behind {topic}",
f"A secondary aspect of {topic}",
f"An unrelated concept to {topic}",
f"A complex theory about {topic}"
],
"correct": 0,
"explanation": f"The main concept of {topic} is the primary idea that students need to understand."
},
{
"question": f"Which of the following best describes {topic}?",
"options": [
f"A simple explanation of {topic}",
f"A complex theory about {topic}",
f"An advanced concept in {topic}",
f"A basic principle of {topic}"
],
"correct": 3,
"explanation": f"{topic} is best described as a basic principle that students should learn."
}
]
selected = questions[question_number % len(questions)]
return {
"type": "Multiple Choice",
"question": selected["question"],
"options": selected["options"],
"correct_answer": selected["options"][selected["correct"]],
"explanation": selected["explanation"]
}
def generate_true_false_question(topic, subject, grade, question_number):
"""Generate a true/false question"""
questions = [
{
"question": f"{topic} is an important concept in {subject}.",
"answer": True,
"explanation": f"Yes, {topic} is indeed an important concept that students need to understand in {subject}."
},
{
"question": f"Understanding {topic} requires advanced knowledge.",
"answer": False,
"explanation": f"While {topic} can be complex, it can be understood at the {grade} grade level with proper instruction."
}
]
selected = questions[question_number % len(questions)]
return {
"type": "True/False",
"question": selected["question"],
"correct_answer": "True" if selected["answer"] else "False",
"explanation": selected["explanation"]
}
def generate_short_answer_question(topic, subject, grade, question_number):
"""Generate a short answer question"""
questions = [
{
"question": f"Explain {topic} in your own words.",
"explanation": f"Students should provide a clear explanation of {topic} using their own understanding."
},
{
"question": f"What are the key components of {topic}?",
"explanation": f"Students should identify and explain the main parts or elements that make up {topic}."
}
]
selected = questions[question_number % len(questions)]
return {
"type": "Short Answer",
"question": selected["question"],
"correct_answer": "Open-ended response",
"explanation": selected["explanation"]
}
def generate_fill_in_blank_question(topic, subject, grade, question_number):
"""Generate a fill in the blank question"""
questions = [
{
"question": f"_______ is the main concept we learned about {topic}.",
"answer": topic,
"explanation": f"The blank should be filled with '{topic}' as it's the main concept being studied."
},
{
"question": f"In {subject}, we study _______ to understand {topic}.",
"answer": "concepts",
"explanation": f"The blank should be filled with 'concepts' as we study various concepts to understand {topic}."
}
]
selected = questions[question_number % len(questions)]
return {
"type": "Fill in the Blank",
"question": selected["question"],
"correct_answer": selected["answer"],
"explanation": selected["explanation"]
}
def format_quiz(content, topic, subject, grade_level, question_count, ai_generated):
"""Format quiz content with proper styling"""
# Process content with images and math
processed_content = process_content_with_images(content, topic, "quiz")
# Apply content styling
styled_content = apply_content_styling(processed_content, "quiz")
# Add header information
header = f"""# π Quiz: {topic}
**Subject:** {subject}
**Grade Level:** {grade_level}
**Number of Questions:** {question_count}
**Generated by:** {'AI Assistant' if ai_generated else 'Educational Algorithms'}
---
"""
return header + styled_content
def format_quiz_from_dict(quiz):
"""Format quiz from dictionary structure"""
content = f"""# π Quiz: {quiz['topic']}
**Subject:** {quiz['subject']}
**Grade Level:** {quiz['grade_level']}
**Number of Questions:** {quiz['question_count']}
**Generated by:** Educational Algorithms
---
"""
for i, question in enumerate(quiz['questions'], 1):
content += f"## Question {i} ({question['type']})\n\n"
content += f"{question['question']}\n\n"
if question['type'] == "Multiple Choice":
for j, option in enumerate(question['options'], 1):
content += f"{j}. {option}\n"
content += "\n"
content += f"**Answer:** {question['correct_answer']}\n\n"
content += f"**Explanation:** {question['explanation']}\n\n"
content += "---\n\n"
return content
|