File size: 14,460 Bytes
39ee121
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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