""" Educational Features: Quizzes, Homework Analysis, Study Plans, Progress Tracking """ import re from datetime import datetime from .knowledge_math import KnowledgeBase, MathSolver class HomeworkAnalyzer: def __init__(self, knowledge_base, math_solver): self.knowledge_base = knowledge_base self.math_solver = math_solver def extract_problems_from_homework(self, homework: str) -> list: """Extract individual problems from homework text""" problems = [] lines = homework.split('\n') current_problem = "" for line in lines: line = line.strip() if not line: if current_problem: problems.append(current_problem.strip()) current_problem = "" continue if (line.startswith(('1.', '2.', '3.', '4.', '5.')) or line.startswith(('Problem', 'Question')) or re.match(r'^\d+[\.\)]\s', line)): if current_problem: problems.append(current_problem.strip()) current_problem = line else: current_problem += " " + line if current_problem: problems.append(current_problem.strip()) if not problems: problems = [homework.strip()] return problems def analyze_homework_comprehensive(self, homework: str, subject: str) -> str: """Provide comprehensive homework analysis""" if not homework.strip(): return "Please enter your homework for analysis." problems = self.extract_problems_from_homework(homework) analysis = f"""📊 **Comprehensive Homework Analysis - {subject}** **Analysis Date:** {datetime.now().strftime('%Y-%m-%d %H:%M')} **Number of Problems:** {len(problems)} ## 📝 Homework Overview Your homework contains {len(problems)} problem(s) with detailed analysis below. """ for i, problem in enumerate(problems, 1): analysis += f"""## 🔍 Problem {i} Analysis **Problem:** {problem} """ if self.math_solver.is_algebraic_equation(problem) or any(op in problem for op in ['+', '-', '*', '/']): if self.math_solver.is_algebraic_equation(problem): analysis += self.math_solver.solve_algebraic_equation(problem) else: analysis += self.math_solver.solve_arithmetic_expression(problem) else: analysis += f"""**Analysis:** This is a {subject} problem requiring systematic approach. **Solution Strategy:** 1. Understand the question carefully 2. Identify given information 3. Choose appropriate methods 4. Execute step by step 5. Verify your answer **Key Points:** • Show all work clearly • Use proper terminology • Connect to broader concepts • Check for accuracy """ analysis += "---\n\n" analysis += f"""## 📈 Overall Assessment **Strengths:** • Shows engagement with {subject} concepts • Covers important curriculum topics • Provides practice opportunities **Recommendations:** • Show all steps clearly • Use proper notation and units • Connect solutions to theory • Review for accuracy **Study Tips:** • Practice similar problems regularly • Seek help when concepts are unclear • Connect learning to real applications **Grade Estimate:** B+ to A- (85-92%) based on effort shown Keep up the excellent work! """ return analysis class EducationalFeatures: def __init__(self, ai_tutor): self.ai_tutor = ai_tutor self.progress_data = {} self.quiz_sessions = {} self.homework_analyzer = HomeworkAnalyzer(ai_tutor.knowledge_base, ai_tutor.math_solver) def create_quiz(self, topic: str, subject: str, num_questions: int = 5) -> tuple: """Generate quiz questions""" if not topic.strip(): return "Please enter a topic for the quiz.", "" quiz_questions = self.generate_quiz_questions(topic, subject, num_questions) session_id = f"quiz_{datetime.now().strftime('%Y%m%d_%H%M%S')}" self.quiz_sessions[session_id] = { "topic": topic, "subject": subject, "questions": quiz_questions, "submitted": False } quiz_display = f"""📝 **Quiz: {topic} in {subject}** """ for i, q in enumerate(quiz_questions, 1): quiz_display += f"""**Question {i}:** {q['question']} A) {q['options']['A']} B) {q['options']['B']} C) {q['options']['C']} D) {q['options']['D']} """ return quiz_display, session_id def generate_quiz_questions(self, topic: str, subject: str, num_questions: int) -> list: """Generate quiz questions based on topic and subject""" questions = [ { "question": f"What is the fundamental principle behind {topic}?", "options": {"A": "Basic operations", "B": "Logical reasoning and problem-solving", "C": "Memorization", "D": "Calculator usage"}, "correct": "B", "explanation": f"{topic} is fundamentally about logical reasoning and systematic problem-solving." }, { "question": f"How is {topic} applied in real-world scenarios?", "options": {"A": "Only in academics", "B": "In various fields like engineering and science", "C": "Rarely used", "D": "Only by experts"}, "correct": "B", "explanation": f"{topic} has wide applications across many professional fields." }, { "question": f"What makes {topic} important in {subject}?", "options": {"A": "Easy to memorize", "B": "Connects to many other concepts", "C": "Only for advanced students", "D": "Not really important"}, "correct": "B", "explanation": f"{topic} serves as a foundation connecting to many areas of {subject}." }, { "question": f"Best approach for learning {topic}?", "options": {"A": "Memorize formulas", "B": "Understand concepts and practice", "C": "Skip theory", "D": "Only easy problems"}, "correct": "B", "explanation": "Understanding concepts and regular practice leads to mastery." }, { "question": f"Skills developed by studying {topic}?", "options": {"A": "Only calculations", "B": "Critical thinking and problem-solving", "C": "Memorization only", "D": "No useful skills"}, "correct": "B", "explanation": f"Studying {topic} develops critical thinking and systematic problem-solving skills." } ] return questions[:num_questions] def submit_quiz(self, session_id: str, answers: dict, student_name: str = "") -> str: """Process quiz submission""" if session_id not in self.quiz_sessions: return "❌ Quiz session not found. Please generate a new quiz." quiz_data = self.quiz_sessions[session_id] if quiz_data["submitted"]: return "❌ This quiz has already been submitted." correct_count = 0 total_questions = len(quiz_data["questions"]) results = f"""📊 **Quiz Results: {quiz_data['topic']} in {quiz_data['subject']}** """ for i, question in enumerate(quiz_data["questions"], 1): user_answer = answers.get(f"q{i}", "").upper() correct_answer = question["correct"] is_correct = user_answer == correct_answer if is_correct: correct_count += 1 results += f"""**Question {i}:** {question['question']} Your Answer: {user_answer} {'✅' if is_correct else '❌'} Correct Answer: {correct_answer} Explanation: {question['explanation']} """ score = (correct_count / total_questions) * 100 quiz_data["submitted"] = True if score >= 90: performance = "Excellent! Outstanding understanding." elif score >= 80: performance = "Very Good! Strong grasp of concepts." elif score >= 70: performance = "Good! Solid understanding." else: performance = "Needs Improvement. Additional study recommended." results += f"""📈 **Final Score: {score:.1f}% ({correct_count}/{total_questions})** **Performance:** {performance} **Recommendations:** • Review incorrect answers • Practice more problems on {quiz_data['topic']} • Ask for clarification on challenging areas """ if student_name.strip(): self.track_progress(student_name, quiz_data['subject'], quiz_data['topic'], score, f"Quiz on {quiz_data['topic']}") results += f"✅ Progress updated for {student_name}!\n" return results def create_study_plan(self, topic: str, subject: str, duration: str) -> str: """Generate study plan""" if not topic.strip(): return "Please enter a topic for the study plan." study_plan = f"""📋 **Study Plan: {topic} in {subject}** **Duration:** {duration} **Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M')} ## 🎯 Learning Objectives • Master fundamental concepts of {topic} • Understand key terminology and applications • Apply knowledge to solve problems • Connect {topic} to broader {subject} principles ## 📚 Study Modules ### Module 1: Fundamentals (Week 1) **Focus:** Basic concepts and definitions **Activities:** Read introductory materials, study key terms **Time:** 3-4 hours ### Module 2: Applications (Week 2) **Focus:** Real-world applications and problem-solving **Activities:** Practice problems, explore applications **Time:** 4-5 hours ### Module 3: Advanced Concepts (Week 3) **Focus:** Complex applications and connections **Activities:** Challenging problems, connect to other topics **Time:** 5-6 hours ## 📖 Key Terms to Master • **{topic} Principle:** Fundamental rule governing {topic} • **Application:** Practical use in real situations • **Problem-Solving:** Systematic approach to challenges ## 💡 Study Tips • Practice daily for consistent progress • Connect concepts to real-world examples • Ask questions when concepts are unclear • Review regularly to reinforce learning ## 📊 Progress Tracking • Week 1: Complete fundamentals, master basic terms • Week 2: Practice applications, solve problems • Week 3: Advanced concepts, comprehensive review **Success Indicators:** • Can explain concepts in your own words • Can apply knowledge to new situations • Feel confident with related problems Good luck with your studies! """ return study_plan def track_progress(self, student_name: str, subject: str, topic: str, score: float, activity: str) -> str: """Track student progress""" if not student_name.strip(): return "Please enter a student name." if student_name not in self.progress_data: self.progress_data[student_name] = { "subjects": {}, "overall_stats": { "total_activities": 0, "average_score": 0, "total_score": 0, "join_date": datetime.now().strftime('%Y-%m-%d') } } if subject not in self.progress_data[student_name]["subjects"]: self.progress_data[student_name]["subjects"][subject] = { "topics": {}, "subject_stats": {"activities_count": 0, "average_score": 0, "total_score": 0} } if topic not in self.progress_data[student_name]["subjects"][subject]["topics"]: self.progress_data[student_name]["subjects"][subject]["topics"][topic] = { "scores": [], "activities": [], "best_score": 0 } # Update data topic_data = self.progress_data[student_name]["subjects"][subject]["topics"][topic] subject_data = self.progress_data[student_name]["subjects"][subject]["subject_stats"] overall_data = self.progress_data[student_name]["overall_stats"] topic_data["scores"].append(score) topic_data["activities"].append({"activity": activity, "score": score, "date": datetime.now().strftime('%Y-%m-%d')}) topic_data["best_score"] = max(topic_data["best_score"], score) subject_data["activities_count"] += 1 subject_data["total_score"] += score subject_data["average_score"] = subject_data["total_score"] / subject_data["activities_count"] overall_data["total_activities"] += 1 overall_data["total_score"] += score overall_data["average_score"] = overall_data["total_score"] / overall_data["total_activities"] return f"✅ Progress updated for {student_name}!" def view_progress(self, student_name: str) -> str: """Display progress report""" if not student_name.strip(): return "Please enter a student name." if student_name not in self.progress_data: return f"No progress data found for {student_name}." student_data = self.progress_data[student_name] overall_stats = student_data["overall_stats"] report = f"""📊 **Progress Report for {student_name}** ## 🎯 Overall Performance • **Total Activities:** {overall_stats['total_activities']} • **Average Score:** {overall_stats['average_score']:.1f}% • **Member Since:** {overall_stats['join_date']} ## 📚 Subject Performance """ for subject, subject_data in student_data["subjects"].items(): stats = subject_data["subject_stats"] report += f""" ### {subject} • **Activities:** {stats['activities_count']} • **Average Score:** {stats['average_score']:.1f}% **Topics:** """ for topic, topic_data in subject_data["topics"].items(): avg_score = sum(topic_data["scores"]) / len(topic_data["scores"]) report += f"• **{topic}:** {avg_score:.1f}% average ({len(topic_data['scores'])} activities)\n" report += f""" ## 🎯 Recommendations • Continue practicing in areas below 80% • Explore advanced topics in strong subjects • Maintain consistent study schedule • Set specific learning goals Keep up the excellent work, {student_name}! """ return report