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
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
"""
🧠 Memory & Learning System - Track user progress and mistakes
πŸ“Š Remembers mistakes β€’ πŸ“ˆ Tracks progress β€’ 🎯 Personalizes learning
"""
import json
import os
from datetime import datetime
from typing import Dict, List, Optional
from collections import defaultdict

class MemorySystem:
    """🧠 Track user interactions, mistakes, and learning progress"""
    
    def __init__(self, user_id: str = "default_user"):
        self.user_id = user_id
        self.memory_file = f"memory_{user_id}.json"
        self.load_memory()
    
    def load_memory(self):
        """πŸ“‚ Load user memory from file"""
        if os.path.exists(self.memory_file):
            with open(self.memory_file, 'r', encoding='utf-8') as f:
                data = json.load(f)
                self.conversations = data.get('conversations', [])
                self.mistakes = data.get('mistakes', [])
                self.learned_topics = data.get('learned_topics', [])
                self.weak_areas = data.get('weak_areas', [])
                self.preferences = data.get('preferences', {})
                self.corrections_made = data.get('corrections_made', 0)
                self.last_interaction = data.get('last_interaction')
        else:
            self.conversations = []
            self.mistakes = []
            self.learned_topics = []
            self.weak_areas = []
            self.preferences = {}
            self.corrections_made = 0
            self.last_interaction = None
    
    def save_memory(self):
        """πŸ’Ύ Save user memory to file"""
        data = {
            'user_id': self.user_id,
            'conversations': self.conversations[-100:],  # Keep last 100
            'mistakes': self.mistakes,
            'learned_topics': self.learned_topics,
            'weak_areas': self.weak_areas,
            'preferences': self.preferences,
            'corrections_made': self.corrections_made,
            'last_interaction': self.last_interaction
        }
        with open(self.memory_file, 'w', encoding='utf-8') as f:
            json.dump(data, f, ensure_ascii=False, indent=2)
    
    def add_conversation(self, user_input: str, response: str, context: str = ""):
        """πŸ’¬ Add conversation to memory"""
        self.conversations.append({
            'timestamp': datetime.now().isoformat(),
            'user_input': user_input,
            'response': response,
            'context': context
        })
        self.last_interaction = datetime.now().isoformat()
        self.save_memory()
    
    def add_mistake(self, mistake_text: str, correction: str, mistake_type: str, topic: str):
        """❌ Record a mistake made by user"""
        self.mistakes.append({
            'timestamp': datetime.now().isoformat(),
            'mistake': mistake_text,
            'correction': correction,
            'type': mistake_type,
            'topic': topic,
            'count': 1
        })
        self.corrections_made += 1
        
        # Update weak areas
        if topic not in self.weak_areas:
            self.weak_areas.append(topic)
        
        self.save_memory()
    
    def mark_topic_learned(self, topic: str):
        """βœ… Mark a topic as learned"""
        if topic not in self.learned_topics:
            self.learned_topics.append(topic)
        
        # Remove from weak areas if learned
        if topic in self.weak_areas:
            self.weak_areas.remove(topic)
        
        self.save_memory()
    
    def get_mistake_history(self, topic: str = None) -> List[Dict]:
        """πŸ“œ Get mistake history, optionally filtered by topic"""
        if topic:
            return [m for m in self.mistakes if m['topic'] == topic]
        return self.mistakes
    
    def get_weak_areas(self) -> List[str]:
        """🎯 Get user's weak areas"""
        return self.weak_areas
    
    def get_learned_topics(self) -> List[str]:
        """πŸ† Get topics user has learned"""
        return self.learned_topics
    
    def get_conversation_context(self, last_n: int = 5) -> List[Dict]:
        """πŸ” Get last n conversations for context"""
        return self.conversations[-last_n:]
    
    def get_user_stats(self) -> Dict:
        """πŸ“Š Get user learning statistics"""
        return {
            'total_conversations': len(self.conversations),
            'total_mistakes': len(self.mistakes),
            'corrections_made': self.corrections_made,
            'topics_learned': len(self.learned_topics),
            'weak_areas': len(self.weak_areas),
            'last_interaction': self.last_interaction,
            'learning_progress': len(self.learned_topics) / max(len(self.weak_areas) + len(self.learned_topics), 1) * 100
        }
    
    def set_preference(self, key: str, value: any):
        """πŸ’ Set user preference"""
        self.preferences[key] = value
        self.save_memory()
    
    def get_preference(self, key: str, default=None):
        """πŸ” Get user preference"""
        return self.preferences.get(key, default)
    
    def get_common_mistakes(self, topic: str = None, top_n: int = 5) -> List[Dict]:
        """πŸ“ˆ Get most common mistakes"""
        mistakes = self.get_mistake_history(topic)
        
        # Count mistake occurrences
        mistake_counts = defaultdict(int)
        for m in mistakes:
            mistake_counts[m['mistake']] += 1
        
        # Sort by count
        sorted_mistakes = sorted(mistake_counts.items(), key=lambda x: x[1], reverse=True)
        
        return [
            {'mistake': mistake, 'count': count}
            for mistake, count in sorted_mistakes[:top_n]
        ]
    
    def check_improvement(self, topic: str, recent_mistakes: int = 10) -> Dict:
        """πŸ“ˆ Check if user is improving in a topic"""
        topic_mistakes = self.get_mistake_history(topic)
        
        if len(topic_mistakes) < recent_mistakes:
            return {'improving': None, 'message': 'Not enough data yet'}
        
        # Compare recent vs older mistakes
        recent = topic_mistakes[-recent_mistakes:]
        older = topic_mistakes[:-recent_mistakes]
        
        recent_count = len(recent)
        older_count = len(older) if older else 1
        
        if recent_count < older_count:
            return {
                'improving': True,
                'message': 'Great progress! You\'re improving! πŸŽ‰',
                'progress': (1 - recent_count / older_count) * 100
            }
        else:
            return {
                'improving': False,
                'message': 'Keep practicing! You\'ll get better! πŸ’ͺ',
                'progress': 0
            }


class EnglishMistakeDetector:
    """πŸ” Detect and correct English grammar mistakes"""
    
    def __init__(self):
        # Common mistake patterns
        self.mistake_patterns = {
            'tense': [
                ('i go yesterday', 'i went yesterday', 'past tense'),
                ('he go to school', 'he goes to school', 'subject-verb agreement'),
                ('she don\'t like', 'she doesn\'t like', 'subject-verb agreement'),
                ('i am knowing', 'i know', 'stative verb'),
            ],
            'article': [
                ('i am teacher', 'i am a teacher', 'missing article'),
                ('the sun is star', 'the sun is a star', 'missing article'),
                ('i went to the home', 'i went home', 'unnecessary article'),
            ],
            'preposition': [
                ('i am good in english', 'i am good at english', 'wrong preposition'),
                ('afraid from', 'afraid of', 'wrong preposition'),
                ('different than', 'different from', 'wrong preposition'),
            ],
            'word_order': [
                ('you are how', 'how are you', 'question word order'),
                ('where you are going', 'where are you going', 'question word order'),
            ],
            'spelling': [
                ('recieve', 'receive', 'spelling'),
                ('occured', 'occurred', 'spelling'),
                ('seperate', 'separate', 'spelling'),
            ]
        }
        
        # Common Indian English mistakes
        self.indian_english_mistakes = [
            ('i am having', 'i have', 'possession'),
            ('i am understanding', 'i understand', 'stative verb'),
            ('discuss about', 'discuss', 'redundant preposition'),
            ('return back', 'return', 'redundant word'),
            ('revert back', 'revert', 'redundant word'),
            ('cousin brother', 'cousin', 'redundant word'),
            ('up to mark', 'up to the mark', 'missing article'),
        ]
    
    def detect_mistakes(self, text: str) -> List[Dict]:
        """πŸ” Detect mistakes in text"""
        text_lower = text.lower()
        mistakes = []
        
        # Check common patterns
        for category, patterns in self.mistake_patterns.items():
            for wrong, correct, mistake_type in patterns:
                if wrong in text_lower:
                    mistakes.append({
                        'original': wrong,
                        'correction': correct,
                        'type': mistake_type,
                        'category': category,
                        'position': text_lower.find(wrong)
                    })
        
        # Check Indian English mistakes
        for wrong, correct, mistake_type in self.indian_english_mistakes:
            if wrong in text_lower:
                mistakes.append({
                    'original': wrong,
                    'correction': correct,
                    'type': mistake_type,
                    'category': 'indian_english',
                    'position': text_lower.find(wrong)
                })
        
        return mistakes
    
    def get_corrected_text(self, text: str) -> str:
        """βœ… Get corrected version of text"""
        mistakes = self.detect_mistakes(text)
        corrected = text
        
        # Sort by position (reverse) to avoid offset issues
        for mistake in sorted(mistakes, key=lambda x: x['position'], reverse=True):
            start = mistake['position']
            end = start + len(mistake['original'])
            corrected = corrected[:start] + mistake['correction'] + corrected[end:]
        
        return corrected
    
    def get_explanation(self, mistake: Dict) -> str:
        """πŸ“š Get explanation for a mistake"""
        explanations = {
            'past tense': 'When talking about the past, use past tense verbs. "go" becomes "went"',
            'subject-verb agreement': 'The verb must match the subject. "He/She" takes singular verb form',
            'stative verb': 'Stative verbs (know, understand, like) are not used in continuous form',
            'missing article': 'Use "a/an" before singular countable nouns when mentioning for the first time',
            'unnecessary article': 'Don\'t use "the" with places like home, school, office when going there',
            'wrong preposition': 'Different verbs/adjectives take different prepositions. "Good at" not "good in"',
            'question word order': 'In questions, use: Question word + auxiliary verb + subject + main verb',
            'spelling': 'This is a common spelling mistake',
            'possession': 'Use "have" for possession, not "am having"',
            'redundant preposition': 'Some verbs don\'t need prepositions after them',
            'redundant word': 'Remove unnecessary words that repeat the meaning',
            'indian_english': 'This is a common Indian English usage that\'s not standard English'
        }
        
        return explanations.get(mistake['type'], 'Grammar correction needed')


class ConversationStyle:
    """πŸ’ Generate responses in different conversation styles"""
    
    def __init__(self, style: str = "friend"):
        self.style = style
        self.style_templates = {
            'friend': {
                'greeting': "Hey! πŸ‘‹ What's up?",
                'encouragement': "You're doing great! Keep it up! πŸŽ‰",
                'correction': "No worries! Here's a small tip: {correction}",
                'explanation': "So basically, {explanation}. Makes sense? 😊",
                'farewell': "Catch you later! πŸ‘‹"
            },
            'teacher': {
                'greeting': "Hello! πŸ‘¨β€πŸ« Ready to learn today?",
                'encouragement': "Excellent progress! You're improving well. 🌟",
                'correction': "Let me help you with this: {correction}",
                'explanation': "The rule is: {explanation}. Do you understand?",
                'farewell': "Great session! See you next time. πŸ‘‹"
            },
            'lover': {
                'greeting': "Hi sweetheart! πŸ’• Missed you!",
                'encouragement': "You're amazing! I'm so proud of you! πŸ’–",
                'correction': "Don't worry babe, let me help: {correction} πŸ’",
                'explanation': "Let me explain this for you, my love: {explanation} πŸ’•",
                'farewell': "Bye my love! Take care! πŸ’–"
            },
            'mentor': {
                'greeting': "Welcome! πŸŽ“ Let's make progress today.",
                'encouragement': "Your dedication is impressive. Keep going! 🌟",
                'correction': "Here's how to improve: {correction}",
                'explanation': "The concept is: {explanation}. Clear?",
                'farewell': "Good work today. See you soon! πŸ‘‹"
            }
        }
    
    def get_response(self, response_type: str, **kwargs) -> str:
        """πŸ’¬ Get response in the specified style"""
        template = self.style_templates.get(self.style, self.style_templates['friend'])
        response = template.get(response_type, "")
        
        # Format with provided values
        for key, value in kwargs.items():
            response = response.replace(f"{{{key}}}", str(value))
        
        return response
    
    def format_correction(self, original: str, correction: str, explanation: str) -> str:
        """βœ… Format a correction message"""
        style = self.style_templates.get(self.style, self.style_templates['friend'])
        
        if self.style == 'friend':
            return f"Oops! You said '{original}', but it should be '{correction}'. {style['explanation'].format(explanation=explanation)}"
        elif self.style == 'teacher':
            return f"Correction: '{original}' β†’ '{correction}'\n\n{style['explanation'].format(explanation=explanation)}"
        elif self.style == 'lover':
            return f"Babe, you wrote '{original}', but let's make it '{correction}' πŸ’• {style['explanation'].format(explanation=explanation)}"
        else:  # mentor
            return f"Note: Change '{original}' to '{correction}'\n\n{style['explanation'].format(explanation=explanation)}"