Spaces:
Running
Running
| """ | |
| 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 | |