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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
from smolagents import CodeAgent, tool
import yaml
from tools.final_answer import FinalAnswerTool
import random

# Mock Model that works without external API calls
class LocalModel:
    def __init__(self):
        self.max_tokens = 2096
        self.temperature = 0.7
        self.model_id = 'local-model'
    
    def generate(self, messages, **kwargs):
        # Simple response generation without external API
        class Response:
            def __init__(self, content):
                self.content = content
        return Response("Using local processing for English tutoring.")

@tool
def explain_word(word: str) -> str:
    """Explains an English word with definition, pronunciation, examples, and usage tips.
    
    Args:
        word: The English word to explain
    
    Returns:
        A comprehensive explanation of the word
    """
    # Enhanced word database with common English words
    word_database = {
        "hello": {
            "definition": "A greeting used when meeting someone or starting a conversation",
            "pronunciation": "heh-LOH",
            "part_of_speech": "interjection, noun",
            "examples": [
                "Hello, how are you today?",
                "She said hello to her neighbor.",
                "A friendly hello can brighten someone's day."
            ],
            "synonyms": ["hi", "greetings", "salutations"],
            "usage_tip": "Used as a casual greeting in informal situations or as a polite greeting in formal situations."
        },
        "beautiful": {
            "definition": "Pleasing to the senses or mind; attractive in appearance",
            "pronunciation": "BYOO-ti-ful",
            "part_of_speech": "adjective",
            "examples": [
                "The sunset was absolutely beautiful.",
                "She has beautiful eyes.",
                "The garden looks beautiful in spring."
            ],
            "synonyms": ["lovely", "gorgeous", "attractive", "stunning"],
            "usage_tip": "Can describe physical appearance, nature, art, or abstract concepts like music."
        },
        "learn": {
            "definition": "To gain knowledge or skill through study, experience, or instruction",
            "pronunciation": "lurn",
            "part_of_speech": "verb",
            "examples": [
                "I want to learn English.",
                "Children learn quickly.",
                "She learned to play the piano."
            ],
            "synonyms": ["study", "acquire", "master", "understand"],
            "usage_tip": "Often followed by 'to' + verb (learn to speak) or 'about' + noun (learn about history)."
        },
        "great": {
            "definition": "Of an extent, amount, or intensity considerably above average; excellent",
            "pronunciation": "grayt",
            "part_of_speech": "adjective",
            "examples": [
                "She did a great job on the project.",
                "The Great Wall of China is amazing.",
                "Great! Let's start the lesson."
            ],
            "synonyms": ["excellent", "wonderful", "fantastic", "outstanding"],
            "usage_tip": "Can be used to describe size, quality, or as an exclamation of approval."
        },
        "friend": {
            "definition": "A person you know well and regard with affection and trust",
            "pronunciation": "frend",
            "part_of_speech": "noun",
            "examples": [
                "She is my best friend.",
                "I made a new friend at school.",
                "Friends help each other."
            ],
            "synonyms": ["buddy", "pal", "companion", "mate"],
            "usage_tip": "Friends are people you choose to spend time with and share experiences."
        },
        "happy": {
            "definition": "Feeling or showing pleasure or contentment",
            "pronunciation": "HAP-ee",
            "part_of_speech": "adjective",
            "examples": [
                "I'm happy to see you!",
                "The children look happy playing.",
                "Happy birthday to you!"
            ],
            "synonyms": ["joyful", "cheerful", "delighted", "glad"],
            "usage_tip": "Used to describe positive emotions and feelings of joy."
        }
    }
    
    word_lower = word.lower().strip()
    
    if word_lower in word_database:
        info = word_database[word_lower]
        response = f"## Word: {word.capitalize()}\n\n"
        response += f"**Definition:** {info['definition']}\n\n"
        response += f"**Pronunciation:** /{info['pronunciation']}/\n\n"
        response += f"**Part of Speech:** {info['part_of_speech']}\n\n"
        response += f"**Examples:**\n"
        for example in info['examples']:
            response += f"- {example}\n"
        response += f"\n**Synonyms:** {', '.join(info['synonyms'])}\n\n"
        response += f"**Usage Tip:** {info['usage_tip']}"
        return response
    else:
        return f"## Word: {word.capitalize()}\n\nI don't have detailed information about '{word}' in my current database. Here are some suggestions:\n\n**How to learn about new words:**\n- Look it up in a dictionary\n- Use it in sentences\n- Find synonyms and antonyms\n- Practice pronunciation\n- Read it in context\n\n**Available words in my database:**\nhello, beautiful, learn, great, friend, happy\n\nWould you like me to explain one of these words or help with grammar lessons?"

@tool
def grammar_lesson(topic: str) -> str:
    """Provides grammar lessons on various English topics.
    
    Args:
        topic: The grammar topic to explain (present_tense, articles, prepositions, etc.)
    
    Returns:
        A detailed grammar lesson with examples
    """
    grammar_lessons = {
        "present_tense": {
            "title": "Present Tense",
            "explanation": "The present tense describes actions happening now or habitual actions.",
            "types": [
                {
                    "name": "Simple Present",
                    "form": "Subject + verb (base form)",
                    "examples": ["I eat breakfast every morning.", "She works at a bank.", "They live in New York."],
                    "usage": "For habits, facts, and general truths"
                },
                {
                    "name": "Present Continuous",
                    "form": "Subject + am/is/are + verb-ing",
                    "examples": ["I am eating lunch now.", "She is working on a project.", "They are watching TV."],
                    "usage": "For actions happening right now"
                }
            ]
        },
        "articles": {
            "title": "Articles (a, an, the)",
            "explanation": "Articles are words that introduce nouns. English has three articles: 'a', 'an', and 'the'.",
            "types": [
                {
                    "name": "Indefinite Articles (a, an)",
                    "form": "'a' before consonant sounds, 'an' before vowel sounds",
                    "examples": ["a book", "an apple", "a university", "an hour"],
                    "usage": "For non-specific, countable singular nouns"
                },
                {
                    "name": "Definite Article (the)",
                    "form": "'the' before specific nouns",
                    "examples": ["the book I'm reading", "the sun", "the United States"],
                    "usage": "For specific nouns, unique things, or previously mentioned items"
                }
            ]
        },
        "prepositions": {
            "title": "Prepositions (in, on, at, etc.)",
            "explanation": "Prepositions show relationships between words, often indicating time, place, or direction.",
            "types": [
                {
                    "name": "Prepositions of Time",
                    "form": "in, on, at",
                    "examples": ["in 2023", "on Monday", "at 3 o'clock", "in the morning"],
                    "usage": "in (months/years), on (days/dates), at (specific times)"
                },
                {
                    "name": "Prepositions of Place",
                    "form": "in, on, at, under, above",
                    "examples": ["in the house", "on the table", "at school", "under the bed"],
                    "usage": "Describe where something is located"
                }
            ]
        },
        "past_tense": {
            "title": "Past Tense",
            "explanation": "Past tense describes actions that happened before now.",
            "types": [
                {
                    "name": "Simple Past",
                    "form": "Subject + verb-ed (regular) or irregular form",
                    "examples": ["I walked to school.", "She ate dinner.", "They went home."],
                    "usage": "For completed actions in the past"
                },
                {
                    "name": "Past Continuous",
                    "form": "Subject + was/were + verb-ing",
                    "examples": ["I was reading a book.", "They were playing soccer.", "She was cooking dinner."],
                    "usage": "For ongoing actions in the past"
                }
            ]
        }
    }
    
    topic_lower = topic.lower().replace(" ", "_")
    
    if topic_lower in grammar_lessons:
        lesson = grammar_lessons[topic_lower]
        response = f"## {lesson['title']}\n\n"
        response += f"{lesson['explanation']}\n\n"
        
        for grammar_type in lesson['types']:
            response += f"### {grammar_type['name']}\n"
            response += f"**Form:** {grammar_type['form']}\n"
            response += f"**Usage:** {grammar_type['usage']}\n"
            response += f"**Examples:**\n"
            for example in grammar_type['examples']:
                response += f"- {example}\n"
            response += "\n"
        
        return response
    else:
        available_topics = list(grammar_lessons.keys())
        return f"I don't have a lesson on '{topic}'. Here are available grammar topics:\n\n" + \
               "\n".join([f"- {topic.replace('_', ' ').title()}" for topic in available_topics]) + \
               "\n\nPlease choose one of these topics for a detailed lesson."

@tool
def practice_exercise(exercise_type: str) -> str:
    """Generates practice exercises for English learning.
    
    Args:
        exercise_type: Type of exercise (vocabulary, grammar, sentence_building)
    
    Returns:
        A practice exercise with questions
    """
    exercises = {
        "vocabulary": [
            {
                "question": "Choose the correct word to complete the sentence:",
                "sentence": "The weather is very _____ today.",
                "options": ["beautiful", "beautifully", "beauty", "beautify"],
                "correct": "beautiful",
                "explanation": "'Beautiful' is an adjective that describes the noun 'weather'."
            },
            {
                "question": "What is the opposite of 'difficult'?",
                "options": ["easy", "hard", "complex", "challenging"],
                "correct": "easy",
                "explanation": "'Easy' is the antonym of 'difficult'."
            },
            {
                "question": "Choose the correct word:",
                "sentence": "I am _____ to meet you.",
                "options": ["happy", "sadly", "anger", "beautiful"],
                "correct": "happy",
                "explanation": "'Happy' is an adjective describing how you feel."
            }
        ],
        "grammar": [
            {
                "question": "Choose the correct article:",
                "sentence": "I saw _____ elephant at the zoo.",
                "options": ["a", "an", "the", "no article"],
                "correct": "an",
                "explanation": "Use 'an' before words starting with vowel sounds. 'Elephant' starts with 'e'."
            },
            {
                "question": "Select the correct tense:",
                "sentence": "She _____ to school every day.",
                "options": ["go", "goes", "going", "went"],
                "correct": "goes",
                "explanation": "For third person singular in simple present, add 's' to the verb."
            },
            {
                "question": "Choose the correct past tense:",
                "sentence": "Yesterday, I _____ a movie.",
                "options": ["watch", "watched", "watching", "will watch"],
                "correct": "watched",
                "explanation": "For past tense of regular verbs, add '-ed' to the base form."
            }
        ],
        "sentence_building": [
            {
                "question": "Arrange these words to make a correct sentence:",
                "words": ["I", "every", "morning", "coffee", "drink"],
                "correct": "I drink coffee every morning.",
                "explanation": "Subject + verb + object + time expression is a common sentence pattern."
            },
            {
                "question": "Complete the sentence with the correct word order:",
                "sentence": "Yesterday, [beautiful/very/a/saw/I/movie]",
                "correct": "Yesterday, I saw a very beautiful movie.",
                "explanation": "Time + subject + verb + article + adverb + adjective + noun"
            },
            {
                "question": "Build a sentence with these words:",
                "words": ["friend", "my", "happy", "is", "very"],
                "correct": "My friend is very happy.",
                "explanation": "Possessive + noun + verb + adverb + adjective"
            }
        ]
    }
    
    if exercise_type in exercises:
        exercise = random.choice(exercises[exercise_type])
        response = f"## {exercise_type.title()} Practice\n\n"
        response += f"**{exercise['question']}**\n\n"
        
        if 'sentence' in exercise:
            response += f"Sentence: {exercise['sentence']}\n\n"
        
        if 'words' in exercise:
            response += f"Words to arrange: {', '.join(exercise['words'])}\n\n"
        
        if 'options' in exercise:
            response += "Options:\n"
            for i, option in enumerate(exercise['options'], 1):
                response += f"{i}. {option}\n"
            response += "\n"
        
        response += f"**Correct Answer:** {exercise['correct']}\n\n"
        response += f"**Explanation:** {exercise['explanation']}"
        
        return response
    else:
        return f"Available exercise types: vocabulary, grammar, sentence_building\n\nPlease choose one of these types for practice."

# Setup with local processing (no external API needed)
final_answer = FinalAnswerTool()

# Create a simple non-API based agent
class SimpleEnglishTutor:
    def __init__(self):
        self.tools = {
            'explain_word': explain_word,
            'grammar_lesson': grammar_lesson,
            'practice_exercise': practice_exercise,
            'final_answer': final_answer
        }
    
    def run(self, query):
        query_lower = query.lower()
        
        # Route queries to appropriate tools
        if 'explain' in query_lower and 'word' in query_lower:
            # Extract word from query
            words = query.split()
            for i, word in enumerate(words):
                if word.lower() == 'word' and i + 1 < len(words):
                    target_word = words[i + 1].strip("'\"")
                    return explain_word(target_word)
            return "Please specify a word to explain. Example: 'Explain the word great'"
        
        elif 'grammar' in query_lower or 'lesson' in query_lower:
            if 'present' in query_lower or 'tense' in query_lower:
                return grammar_lesson('present_tense')
            elif 'article' in query_lower:
                return grammar_lesson('articles')
            elif 'preposition' in query_lower:
                return grammar_lesson('prepositions')
            elif 'past' in query_lower:
                return grammar_lesson('past_tense')
            else:
                return grammar_lesson('present_tense')  # default
        
        elif 'exercise' in query_lower or 'practice' in query_lower:
            if 'vocabulary' in query_lower:
                return practice_exercise('vocabulary')
            elif 'grammar' in query_lower:
                return practice_exercise('grammar')
            elif 'sentence' in query_lower:
                return practice_exercise('sentence_building')
            else:
                return practice_exercise('vocabulary')  # default
        
        else:
            # General help
            return """## Welcome to English Tutor! 🇬🇧

I can help you with:

**📚 Word Explanations**
- Ask: "Explain the word [word]"
- Available words: hello, beautiful, learn, great, friend, happy

**📖 Grammar Lessons**
- Present Tense
- Articles (a, an, the)  
- Prepositions
- Past Tense

**✏️ Practice Exercises**
- Vocabulary practice
- Grammar exercises
- Sentence building

**Examples:**
- "Explain the word great"
- "Give me a grammar lesson on articles"
- "I want vocabulary practice"

How can I help you improve your English today?"""

# Create agent instance
agent = SimpleEnglishTutor()

# Create a simple Gradio UI
try:
    import gradio as gr
    
    def create_ui():
        with gr.Blocks(theme=gr.themes.Soft(), title="English Tutor AI") as demo:
            gr.Markdown("# 🇬🇧 English Tutor AI")
            gr.Markdown("Improve your English with AI assistance! No external API required.")
            
            with gr.Tab("Word Explanation"):
                with gr.Row():
                    word_input = gr.Textbox(
                        label="Enter an English word",
                        placeholder="e.g., beautiful, learn, hello, great, friend, happy"
                    )
                    word_btn = gr.Button("Explain Word", variant="primary")
                word_output = gr.Markdown()
                
                def explain_word_handler(word):
                    if word:
                        return agent.run(f"Explain the word {word}")
                    return "Please enter a word to explain."
                
                word_btn.click(
                    explain_word_handler,
                    inputs=[word_input],
                    outputs=[word_output]
                )
            
            with gr.Tab("Grammar Lessons"):
                with gr.Row():
                    grammar_topic = gr.Radio(
                        ["Present Tense", "Articles", "Prepositions", "Past Tense"],
                        label="Choose a grammar topic"
                    )
                    grammar_btn = gr.Button("Get Lesson", variant="primary")
                grammar_output = gr.Markdown()
                
                def grammar_handler(topic):
                    if topic:
                        return agent.run(f"Give me a grammar lesson on {topic}")
                    return "Please select a grammar topic."
                
                grammar_btn.click(
                    grammar_handler,
                    inputs=[grammar_topic],
                    outputs=[grammar_output]
                )
            
            with gr.Tab("Practice Exercises"):
                with gr.Row():
                    exercise_type = gr.Radio(
                        ["Vocabulary", "Grammar", "Sentence Building"],
                        label="Choose exercise type"
                    )
                    exercise_btn = gr.Button("Get Exercise", variant="primary")
                exercise_output = gr.Markdown()
                
                def exercise_handler(ex_type):
                    if ex_type:
                        return agent.run(f"Give me a {ex_type.lower()} practice exercise")
                    return "Please select an exercise type."
                
                exercise_btn.click(
                    exercise_handler,
                    inputs=[exercise_type],
                    outputs=[exercise_output]
                )
            
            with gr.Tab("Free Chat"):
                with gr.Row():
                    chat_input = gr.Textbox(
                        label="Ask anything about English",
                        placeholder="e.g., Explain the word great, Give me grammar lesson"
                    )
                    chat_btn = gr.Button("Ask", variant="primary")
                chat_output = gr.Markdown()
                
                chat_btn.click(
                    agent.run,
                    inputs=[chat_input],
                    outputs=[chat_output]
                )
                
                # Show welcome message by default
                demo.load(lambda: agent.run(""), outputs=[chat_output])
        
        return demo
    
    # Launch the English Tutor
    if __name__ == "__main__":
        demo = create_ui()
        demo.launch()
        
except ImportError:
    print("Gradio not available. Running in console mode.")
    if __name__ == "__main__":
        print("English Tutor AI - Console Mode")
        print("=" * 40)
        print(agent.run(""))
        
        while True:
            try:
                user_input = input("\nYou: ")
                if user_input.lower() in ['quit', 'exit', 'bye']:
                    print("Goodbye! Keep practicing your English!")
                    break
                print("\nTutor:", agent.run(user_input))
            except KeyboardInterrupt:
                print("\nGoodbye! Keep practicing your English!")
                break