RLikhitha commited on
Commit
39ee121
Β·
verified Β·
1 Parent(s): e185086

Create features.py

Browse files
Files changed (1) hide show
  1. core/features.py +392 -0
core/features.py ADDED
@@ -0,0 +1,392 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Educational Features: Quizzes, Homework Analysis, Study Plans, Progress Tracking
3
+ """
4
+
5
+ import re
6
+ from datetime import datetime
7
+ from .knowledge_math import KnowledgeBase, MathSolver
8
+
9
+ class HomeworkAnalyzer:
10
+ def __init__(self, knowledge_base, math_solver):
11
+ self.knowledge_base = knowledge_base
12
+ self.math_solver = math_solver
13
+
14
+ def extract_problems_from_homework(self, homework: str) -> list:
15
+ """Extract individual problems from homework text"""
16
+ problems = []
17
+ lines = homework.split('\n')
18
+ current_problem = ""
19
+
20
+ for line in lines:
21
+ line = line.strip()
22
+ if not line:
23
+ if current_problem:
24
+ problems.append(current_problem.strip())
25
+ current_problem = ""
26
+ continue
27
+
28
+ if (line.startswith(('1.', '2.', '3.', '4.', '5.')) or
29
+ line.startswith(('Problem', 'Question')) or
30
+ re.match(r'^\d+[\.\)]\s', line)):
31
+ if current_problem:
32
+ problems.append(current_problem.strip())
33
+ current_problem = line
34
+ else:
35
+ current_problem += " " + line
36
+
37
+ if current_problem:
38
+ problems.append(current_problem.strip())
39
+
40
+ if not problems:
41
+ problems = [homework.strip()]
42
+
43
+ return problems
44
+
45
+ def analyze_homework_comprehensive(self, homework: str, subject: str) -> str:
46
+ """Provide comprehensive homework analysis"""
47
+ if not homework.strip():
48
+ return "Please enter your homework for analysis."
49
+
50
+ problems = self.extract_problems_from_homework(homework)
51
+
52
+ analysis = f"""πŸ“Š **Comprehensive Homework Analysis - {subject}**
53
+ **Analysis Date:** {datetime.now().strftime('%Y-%m-%d %H:%M')}
54
+ **Number of Problems:** {len(problems)}
55
+
56
+ ## πŸ“ Homework Overview
57
+ Your homework contains {len(problems)} problem(s) with detailed analysis below.
58
+
59
+ """
60
+
61
+ for i, problem in enumerate(problems, 1):
62
+ analysis += f"""## πŸ” Problem {i} Analysis
63
+
64
+ **Problem:** {problem}
65
+
66
+ """
67
+
68
+ if self.math_solver.is_algebraic_equation(problem) or any(op in problem for op in ['+', '-', '*', '/']):
69
+ if self.math_solver.is_algebraic_equation(problem):
70
+ analysis += self.math_solver.solve_algebraic_equation(problem)
71
+ else:
72
+ analysis += self.math_solver.solve_arithmetic_expression(problem)
73
+ else:
74
+ analysis += f"""**Analysis:**
75
+ This is a {subject} problem requiring systematic approach.
76
+
77
+ **Solution Strategy:**
78
+ 1. Understand the question carefully
79
+ 2. Identify given information
80
+ 3. Choose appropriate methods
81
+ 4. Execute step by step
82
+ 5. Verify your answer
83
+
84
+ **Key Points:**
85
+ β€’ Show all work clearly
86
+ β€’ Use proper terminology
87
+ β€’ Connect to broader concepts
88
+ β€’ Check for accuracy
89
+
90
+ """
91
+ analysis += "---\n\n"
92
+
93
+ analysis += f"""## πŸ“ˆ Overall Assessment
94
+
95
+ **Strengths:**
96
+ β€’ Shows engagement with {subject} concepts
97
+ β€’ Covers important curriculum topics
98
+ β€’ Provides practice opportunities
99
+
100
+ **Recommendations:**
101
+ β€’ Show all steps clearly
102
+ β€’ Use proper notation and units
103
+ β€’ Connect solutions to theory
104
+ β€’ Review for accuracy
105
+
106
+ **Study Tips:**
107
+ β€’ Practice similar problems regularly
108
+ β€’ Seek help when concepts are unclear
109
+ β€’ Connect learning to real applications
110
+
111
+ **Grade Estimate:** B+ to A- (85-92%) based on effort shown
112
+
113
+ Keep up the excellent work!
114
+ """
115
+ return analysis
116
+
117
+ class EducationalFeatures:
118
+ def __init__(self, ai_tutor):
119
+ self.ai_tutor = ai_tutor
120
+ self.progress_data = {}
121
+ self.quiz_sessions = {}
122
+ self.homework_analyzer = HomeworkAnalyzer(ai_tutor.knowledge_base, ai_tutor.math_solver)
123
+
124
+ def create_quiz(self, topic: str, subject: str, num_questions: int = 5) -> tuple:
125
+ """Generate quiz questions"""
126
+ if not topic.strip():
127
+ return "Please enter a topic for the quiz.", ""
128
+
129
+ quiz_questions = self.generate_quiz_questions(topic, subject, num_questions)
130
+ session_id = f"quiz_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
131
+
132
+ self.quiz_sessions[session_id] = {
133
+ "topic": topic,
134
+ "subject": subject,
135
+ "questions": quiz_questions,
136
+ "submitted": False
137
+ }
138
+
139
+ quiz_display = f"""πŸ“ **Quiz: {topic} in {subject}**
140
+
141
+ """
142
+ for i, q in enumerate(quiz_questions, 1):
143
+ quiz_display += f"""**Question {i}:** {q['question']}
144
+ A) {q['options']['A']}
145
+ B) {q['options']['B']}
146
+ C) {q['options']['C']}
147
+ D) {q['options']['D']}
148
+
149
+ """
150
+ return quiz_display, session_id
151
+
152
+ def generate_quiz_questions(self, topic: str, subject: str, num_questions: int) -> list:
153
+ """Generate quiz questions based on topic and subject"""
154
+ questions = [
155
+ {
156
+ "question": f"What is the fundamental principle behind {topic}?",
157
+ "options": {"A": "Basic operations", "B": "Logical reasoning and problem-solving", "C": "Memorization", "D": "Calculator usage"},
158
+ "correct": "B",
159
+ "explanation": f"{topic} is fundamentally about logical reasoning and systematic problem-solving."
160
+ },
161
+ {
162
+ "question": f"How is {topic} applied in real-world scenarios?",
163
+ "options": {"A": "Only in academics", "B": "In various fields like engineering and science", "C": "Rarely used", "D": "Only by experts"},
164
+ "correct": "B",
165
+ "explanation": f"{topic} has wide applications across many professional fields."
166
+ },
167
+ {
168
+ "question": f"What makes {topic} important in {subject}?",
169
+ "options": {"A": "Easy to memorize", "B": "Connects to many other concepts", "C": "Only for advanced students", "D": "Not really important"},
170
+ "correct": "B",
171
+ "explanation": f"{topic} serves as a foundation connecting to many areas of {subject}."
172
+ },
173
+ {
174
+ "question": f"Best approach for learning {topic}?",
175
+ "options": {"A": "Memorize formulas", "B": "Understand concepts and practice", "C": "Skip theory", "D": "Only easy problems"},
176
+ "correct": "B",
177
+ "explanation": "Understanding concepts and regular practice leads to mastery."
178
+ },
179
+ {
180
+ "question": f"Skills developed by studying {topic}?",
181
+ "options": {"A": "Only calculations", "B": "Critical thinking and problem-solving", "C": "Memorization only", "D": "No useful skills"},
182
+ "correct": "B",
183
+ "explanation": f"Studying {topic} develops critical thinking and systematic problem-solving skills."
184
+ }
185
+ ]
186
+ return questions[:num_questions]
187
+
188
+ def submit_quiz(self, session_id: str, answers: dict, student_name: str = "") -> str:
189
+ """Process quiz submission"""
190
+ if session_id not in self.quiz_sessions:
191
+ return "❌ Quiz session not found. Please generate a new quiz."
192
+
193
+ quiz_data = self.quiz_sessions[session_id]
194
+ if quiz_data["submitted"]:
195
+ return "❌ This quiz has already been submitted."
196
+
197
+ correct_count = 0
198
+ total_questions = len(quiz_data["questions"])
199
+
200
+ results = f"""πŸ“Š **Quiz Results: {quiz_data['topic']} in {quiz_data['subject']}**
201
+
202
+ """
203
+
204
+ for i, question in enumerate(quiz_data["questions"], 1):
205
+ user_answer = answers.get(f"q{i}", "").upper()
206
+ correct_answer = question["correct"]
207
+ is_correct = user_answer == correct_answer
208
+
209
+ if is_correct:
210
+ correct_count += 1
211
+
212
+ results += f"""**Question {i}:** {question['question']}
213
+ Your Answer: {user_answer} {'βœ…' if is_correct else '❌'}
214
+ Correct Answer: {correct_answer}
215
+ Explanation: {question['explanation']}
216
+
217
+ """
218
+
219
+ score = (correct_count / total_questions) * 100
220
+ quiz_data["submitted"] = True
221
+
222
+ if score >= 90:
223
+ performance = "Excellent! Outstanding understanding."
224
+ elif score >= 80:
225
+ performance = "Very Good! Strong grasp of concepts."
226
+ elif score >= 70:
227
+ performance = "Good! Solid understanding."
228
+ else:
229
+ performance = "Needs Improvement. Additional study recommended."
230
+
231
+ results += f"""πŸ“ˆ **Final Score: {score:.1f}% ({correct_count}/{total_questions})**
232
+ **Performance:** {performance}
233
+
234
+ **Recommendations:**
235
+ β€’ Review incorrect answers
236
+ β€’ Practice more problems on {quiz_data['topic']}
237
+ β€’ Ask for clarification on challenging areas
238
+ """
239
+
240
+ if student_name.strip():
241
+ self.track_progress(student_name, quiz_data['subject'], quiz_data['topic'], score, f"Quiz on {quiz_data['topic']}")
242
+ results += f"βœ… Progress updated for {student_name}!\n"
243
+
244
+ return results
245
+
246
+ def create_study_plan(self, topic: str, subject: str, duration: str) -> str:
247
+ """Generate study plan"""
248
+ if not topic.strip():
249
+ return "Please enter a topic for the study plan."
250
+
251
+ study_plan = f"""πŸ“‹ **Study Plan: {topic} in {subject}**
252
+ **Duration:** {duration}
253
+ **Generated:** {datetime.now().strftime('%Y-%m-%d %H:%M')}
254
+
255
+ ## 🎯 Learning Objectives
256
+ β€’ Master fundamental concepts of {topic}
257
+ β€’ Understand key terminology and applications
258
+ β€’ Apply knowledge to solve problems
259
+ β€’ Connect {topic} to broader {subject} principles
260
+
261
+ ## πŸ“š Study Modules
262
+
263
+ ### Module 1: Fundamentals (Week 1)
264
+ **Focus:** Basic concepts and definitions
265
+ **Activities:** Read introductory materials, study key terms
266
+ **Time:** 3-4 hours
267
+
268
+ ### Module 2: Applications (Week 2)
269
+ **Focus:** Real-world applications and problem-solving
270
+ **Activities:** Practice problems, explore applications
271
+ **Time:** 4-5 hours
272
+
273
+ ### Module 3: Advanced Concepts (Week 3)
274
+ **Focus:** Complex applications and connections
275
+ **Activities:** Challenging problems, connect to other topics
276
+ **Time:** 5-6 hours
277
+
278
+ ## πŸ“– Key Terms to Master
279
+ β€’ **{topic} Principle:** Fundamental rule governing {topic}
280
+ β€’ **Application:** Practical use in real situations
281
+ β€’ **Problem-Solving:** Systematic approach to challenges
282
+
283
+ ## πŸ’‘ Study Tips
284
+ β€’ Practice daily for consistent progress
285
+ β€’ Connect concepts to real-world examples
286
+ β€’ Ask questions when concepts are unclear
287
+ β€’ Review regularly to reinforce learning
288
+
289
+ ## πŸ“Š Progress Tracking
290
+ β€’ Week 1: Complete fundamentals, master basic terms
291
+ β€’ Week 2: Practice applications, solve problems
292
+ β€’ Week 3: Advanced concepts, comprehensive review
293
+
294
+ **Success Indicators:**
295
+ β€’ Can explain concepts in your own words
296
+ β€’ Can apply knowledge to new situations
297
+ β€’ Feel confident with related problems
298
+
299
+ Good luck with your studies!
300
+ """
301
+ return study_plan
302
+
303
+ def track_progress(self, student_name: str, subject: str, topic: str, score: float, activity: str) -> str:
304
+ """Track student progress"""
305
+ if not student_name.strip():
306
+ return "Please enter a student name."
307
+
308
+ if student_name not in self.progress_data:
309
+ self.progress_data[student_name] = {
310
+ "subjects": {},
311
+ "overall_stats": {
312
+ "total_activities": 0,
313
+ "average_score": 0,
314
+ "total_score": 0,
315
+ "join_date": datetime.now().strftime('%Y-%m-%d')
316
+ }
317
+ }
318
+
319
+ if subject not in self.progress_data[student_name]["subjects"]:
320
+ self.progress_data[student_name]["subjects"][subject] = {
321
+ "topics": {},
322
+ "subject_stats": {"activities_count": 0, "average_score": 0, "total_score": 0}
323
+ }
324
+
325
+ if topic not in self.progress_data[student_name]["subjects"][subject]["topics"]:
326
+ self.progress_data[student_name]["subjects"][subject]["topics"][topic] = {
327
+ "scores": [], "activities": [], "best_score": 0
328
+ }
329
+
330
+ # Update data
331
+ topic_data = self.progress_data[student_name]["subjects"][subject]["topics"][topic]
332
+ subject_data = self.progress_data[student_name]["subjects"][subject]["subject_stats"]
333
+ overall_data = self.progress_data[student_name]["overall_stats"]
334
+
335
+ topic_data["scores"].append(score)
336
+ topic_data["activities"].append({"activity": activity, "score": score, "date": datetime.now().strftime('%Y-%m-%d')})
337
+ topic_data["best_score"] = max(topic_data["best_score"], score)
338
+
339
+ subject_data["activities_count"] += 1
340
+ subject_data["total_score"] += score
341
+ subject_data["average_score"] = subject_data["total_score"] / subject_data["activities_count"]
342
+
343
+ overall_data["total_activities"] += 1
344
+ overall_data["total_score"] += score
345
+ overall_data["average_score"] = overall_data["total_score"] / overall_data["total_activities"]
346
+
347
+ return f"βœ… Progress updated for {student_name}!"
348
+
349
+ def view_progress(self, student_name: str) -> str:
350
+ """Display progress report"""
351
+ if not student_name.strip():
352
+ return "Please enter a student name."
353
+
354
+ if student_name not in self.progress_data:
355
+ return f"No progress data found for {student_name}."
356
+
357
+ student_data = self.progress_data[student_name]
358
+ overall_stats = student_data["overall_stats"]
359
+
360
+ report = f"""πŸ“Š **Progress Report for {student_name}**
361
+
362
+ ## 🎯 Overall Performance
363
+ β€’ **Total Activities:** {overall_stats['total_activities']}
364
+ β€’ **Average Score:** {overall_stats['average_score']:.1f}%
365
+ β€’ **Member Since:** {overall_stats['join_date']}
366
+
367
+ ## πŸ“š Subject Performance
368
+ """
369
+
370
+ for subject, subject_data in student_data["subjects"].items():
371
+ stats = subject_data["subject_stats"]
372
+ report += f"""
373
+ ### {subject}
374
+ β€’ **Activities:** {stats['activities_count']}
375
+ β€’ **Average Score:** {stats['average_score']:.1f}%
376
+
377
+ **Topics:**
378
+ """
379
+ for topic, topic_data in subject_data["topics"].items():
380
+ avg_score = sum(topic_data["scores"]) / len(topic_data["scores"])
381
+ report += f"β€’ **{topic}:** {avg_score:.1f}% average ({len(topic_data['scores'])} activities)\n"
382
+
383
+ report += f"""
384
+ ## 🎯 Recommendations
385
+ β€’ Continue practicing in areas below 80%
386
+ β€’ Explore advanced topics in strong subjects
387
+ β€’ Maintain consistent study schedule
388
+ β€’ Set specific learning goals
389
+
390
+ Keep up the excellent work, {student_name}!
391
+ """
392
+ return report