Spaces:
Sleeping
Sleeping
Download content_generators.py from brightmind-ai/test: direct link, hf CLI and curl.
- Browser
- Download file 22.4 kB
-
https://huggingface.co/spaces/brightmind-ai/test/resolve/main/content_generators.py
- Command line
-
hf download hf://spaces/brightmind-ai/test/content_generators.py
-
curl -L -o content_generators.py https://huggingface.co/spaces/brightmind-ai/test/resolve/main/content_generators.py
22.4 kB
| """ | |
| 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 | |