RozzaCreat commited on
Commit
966dfe0
·
verified ·
1 Parent(s): d7a0403

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +368 -1
app.py CHANGED
@@ -152,4 +152,371 @@ def grammar_lesson(topic: str) -> str:
152
  "articles": {
153
  "title": "Articles (a, an, the)",
154
  "explanation": "Articles are words that introduce nouns. English has three articles: 'a', 'an', and 'the'.",
155
- "types": [
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  "articles": {
153
  "title": "Articles (a, an, the)",
154
  "explanation": "Articles are words that introduce nouns. English has three articles: 'a', 'an', and 'the'.",
155
+ "types": [
156
+ {
157
+ "name": "Indefinite Articles (a, an)",
158
+ "form": "'a' before consonant sounds, 'an' before vowel sounds",
159
+ "examples": ["a book", "an apple", "a university", "an hour"],
160
+ "usage": "For non-specific, countable singular nouns"
161
+ },
162
+ {
163
+ "name": "Definite Article (the)",
164
+ "form": "'the' before specific nouns",
165
+ "examples": ["the book I'm reading", "the sun", "the United States"],
166
+ "usage": "For specific nouns, unique things, or previously mentioned items"
167
+ }
168
+ ]
169
+ },
170
+ "prepositions": {
171
+ "title": "Prepositions (in, on, at, etc.)",
172
+ "explanation": "Prepositions show relationships between words, often indicating time, place, or direction.",
173
+ "types": [
174
+ {
175
+ "name": "Prepositions of Time",
176
+ "form": "in, on, at",
177
+ "examples": ["in 2023", "on Monday", "at 3 o'clock", "in the morning"],
178
+ "usage": "in (months/years), on (days/dates), at (specific times)"
179
+ },
180
+ {
181
+ "name": "Prepositions of Place",
182
+ "form": "in, on, at, under, above",
183
+ "examples": ["in the house", "on the table", "at school", "under the bed"],
184
+ "usage": "Describe where something is located"
185
+ }
186
+ ]
187
+ },
188
+ "past_tense": {
189
+ "title": "Past Tense",
190
+ "explanation": "Past tense describes actions that happened before now.",
191
+ "types": [
192
+ {
193
+ "name": "Simple Past",
194
+ "form": "Subject + verb-ed (regular) or irregular form",
195
+ "examples": ["I walked to school.", "She ate dinner.", "They went home."],
196
+ "usage": "For completed actions in the past"
197
+ },
198
+ {
199
+ "name": "Past Continuous",
200
+ "form": "Subject + was/were + verb-ing",
201
+ "examples": ["I was reading a book.", "They were playing soccer.", "She was cooking dinner."],
202
+ "usage": "For ongoing actions in the past"
203
+ }
204
+ ]
205
+ }
206
+ }
207
+
208
+ topic_lower = topic.lower().replace(" ", "_")
209
+
210
+ if topic_lower in grammar_lessons:
211
+ lesson = grammar_lessons[topic_lower]
212
+ response = f"## {lesson['title']}\n\n"
213
+ response += f"{lesson['explanation']}\n\n"
214
+
215
+ for grammar_type in lesson['types']:
216
+ response += f"### {grammar_type['name']}\n"
217
+ response += f"**Form:** {grammar_type['form']}\n"
218
+ response += f"**Usage:** {grammar_type['usage']}\n"
219
+ response += f"**Examples:**\n"
220
+ for example in grammar_type['examples']:
221
+ response += f"- {example}\n"
222
+ response += "\n"
223
+
224
+ return response
225
+ else:
226
+ available_topics = list(grammar_lessons.keys())
227
+ return f"I don't have a lesson on '{topic}'. Here are available grammar topics:\n\n" + \
228
+ "\n".join([f"- {topic.replace('_', ' ').title()}" for topic in available_topics]) + \
229
+ "\n\nPlease choose one of these topics for a detailed lesson."
230
+
231
+ @tool
232
+ def practice_exercise(exercise_type: str) -> str:
233
+ """Generates practice exercises for English learning.
234
+
235
+ Args:
236
+ exercise_type: Type of exercise (vocabulary, grammar, sentence_building)
237
+
238
+ Returns:
239
+ A practice exercise with questions
240
+ """
241
+ exercises = {
242
+ "vocabulary": [
243
+ {
244
+ "question": "Choose the correct word to complete the sentence:",
245
+ "sentence": "The weather is very _____ today.",
246
+ "options": ["beautiful", "beautifully", "beauty", "beautify"],
247
+ "correct": "beautiful",
248
+ "explanation": "'Beautiful' is an adjective that describes the noun 'weather'."
249
+ },
250
+ {
251
+ "question": "What is the opposite of 'difficult'?",
252
+ "options": ["easy", "hard", "complex", "challenging"],
253
+ "correct": "easy",
254
+ "explanation": "'Easy' is the antonym of 'difficult'."
255
+ },
256
+ {
257
+ "question": "Choose the correct word:",
258
+ "sentence": "I am _____ to meet you.",
259
+ "options": ["happy", "sadly", "anger", "beautiful"],
260
+ "correct": "happy",
261
+ "explanation": "'Happy' is an adjective describing how you feel."
262
+ }
263
+ ],
264
+ "grammar": [
265
+ {
266
+ "question": "Choose the correct article:",
267
+ "sentence": "I saw _____ elephant at the zoo.",
268
+ "options": ["a", "an", "the", "no article"],
269
+ "correct": "an",
270
+ "explanation": "Use 'an' before words starting with vowel sounds. 'Elephant' starts with 'e'."
271
+ },
272
+ {
273
+ "question": "Select the correct tense:",
274
+ "sentence": "She _____ to school every day.",
275
+ "options": ["go", "goes", "going", "went"],
276
+ "correct": "goes",
277
+ "explanation": "For third person singular in simple present, add 's' to the verb."
278
+ },
279
+ {
280
+ "question": "Choose the correct past tense:",
281
+ "sentence": "Yesterday, I _____ a movie.",
282
+ "options": ["watch", "watched", "watching", "will watch"],
283
+ "correct": "watched",
284
+ "explanation": "For past tense of regular verbs, add '-ed' to the base form."
285
+ }
286
+ ],
287
+ "sentence_building": [
288
+ {
289
+ "question": "Arrange these words to make a correct sentence:",
290
+ "words": ["I", "every", "morning", "coffee", "drink"],
291
+ "correct": "I drink coffee every morning.",
292
+ "explanation": "Subject + verb + object + time expression is a common sentence pattern."
293
+ },
294
+ {
295
+ "question": "Complete the sentence with the correct word order:",
296
+ "sentence": "Yesterday, [beautiful/very/a/saw/I/movie]",
297
+ "correct": "Yesterday, I saw a very beautiful movie.",
298
+ "explanation": "Time + subject + verb + article + adverb + adjective + noun"
299
+ },
300
+ {
301
+ "question": "Build a sentence with these words:",
302
+ "words": ["friend", "my", "happy", "is", "very"],
303
+ "correct": "My friend is very happy.",
304
+ "explanation": "Possessive + noun + verb + adverb + adjective"
305
+ }
306
+ ]
307
+ }
308
+
309
+ if exercise_type in exercises:
310
+ exercise = random.choice(exercises[exercise_type])
311
+ response = f"## {exercise_type.title()} Practice\n\n"
312
+ response += f"**{exercise['question']}**\n\n"
313
+
314
+ if 'sentence' in exercise:
315
+ response += f"Sentence: {exercise['sentence']}\n\n"
316
+
317
+ if 'words' in exercise:
318
+ response += f"Words to arrange: {', '.join(exercise['words'])}\n\n"
319
+
320
+ if 'options' in exercise:
321
+ response += "Options:\n"
322
+ for i, option in enumerate(exercise['options'], 1):
323
+ response += f"{i}. {option}\n"
324
+ response += "\n"
325
+
326
+ response += f"**Correct Answer:** {exercise['correct']}\n\n"
327
+ response += f"**Explanation:** {exercise['explanation']}"
328
+
329
+ return response
330
+ else:
331
+ return f"Available exercise types: vocabulary, grammar, sentence_building\n\nPlease choose one of these types for practice."
332
+
333
+ # Setup with local processing (no external API needed)
334
+ final_answer = FinalAnswerTool()
335
+
336
+ # Create a simple non-API based agent
337
+ class SimpleEnglishTutor:
338
+ def __init__(self):
339
+ self.tools = {
340
+ 'explain_word': explain_word,
341
+ 'grammar_lesson': grammar_lesson,
342
+ 'practice_exercise': practice_exercise,
343
+ 'final_answer': final_answer
344
+ }
345
+
346
+ def run(self, query):
347
+ query_lower = query.lower()
348
+
349
+ # Route queries to appropriate tools
350
+ if 'explain' in query_lower and 'word' in query_lower:
351
+ # Extract word from query
352
+ words = query.split()
353
+ for i, word in enumerate(words):
354
+ if word.lower() == 'word' and i + 1 < len(words):
355
+ target_word = words[i + 1].strip("'\"")
356
+ return explain_word(target_word)
357
+ return "Please specify a word to explain. Example: 'Explain the word great'"
358
+
359
+ elif 'grammar' in query_lower or 'lesson' in query_lower:
360
+ if 'present' in query_lower or 'tense' in query_lower:
361
+ return grammar_lesson('present_tense')
362
+ elif 'article' in query_lower:
363
+ return grammar_lesson('articles')
364
+ elif 'preposition' in query_lower:
365
+ return grammar_lesson('prepositions')
366
+ elif 'past' in query_lower:
367
+ return grammar_lesson('past_tense')
368
+ else:
369
+ return grammar_lesson('present_tense') # default
370
+
371
+ elif 'exercise' in query_lower or 'practice' in query_lower:
372
+ if 'vocabulary' in query_lower:
373
+ return practice_exercise('vocabulary')
374
+ elif 'grammar' in query_lower:
375
+ return practice_exercise('grammar')
376
+ elif 'sentence' in query_lower:
377
+ return practice_exercise('sentence_building')
378
+ else:
379
+ return practice_exercise('vocabulary') # default
380
+
381
+ else:
382
+ # General help
383
+ return """## Welcome to English Tutor! 🇬🇧
384
+
385
+ I can help you with:
386
+
387
+ **📚 Word Explanations**
388
+ - Ask: "Explain the word [word]"
389
+ - Available words: hello, beautiful, learn, great, friend, happy
390
+
391
+ **📖 Grammar Lessons**
392
+ - Present Tense
393
+ - Articles (a, an, the)
394
+ - Prepositions
395
+ - Past Tense
396
+
397
+ **✏️ Practice Exercises**
398
+ - Vocabulary practice
399
+ - Grammar exercises
400
+ - Sentence building
401
+
402
+ **Examples:**
403
+ - "Explain the word great"
404
+ - "Give me a grammar lesson on articles"
405
+ - "I want vocabulary practice"
406
+
407
+ How can I help you improve your English today?"""
408
+
409
+ # Create agent instance
410
+ agent = SimpleEnglishTutor()
411
+
412
+ # Create a simple Gradio UI
413
+ try:
414
+ import gradio as gr
415
+
416
+ def create_ui():
417
+ with gr.Blocks(theme=gr.themes.Soft(), title="English Tutor AI") as demo:
418
+ gr.Markdown("# 🇬🇧 English Tutor AI")
419
+ gr.Markdown("Improve your English with AI assistance! No external API required.")
420
+
421
+ with gr.Tab("Word Explanation"):
422
+ with gr.Row():
423
+ word_input = gr.Textbox(
424
+ label="Enter an English word",
425
+ placeholder="e.g., beautiful, learn, hello, great, friend, happy"
426
+ )
427
+ word_btn = gr.Button("Explain Word", variant="primary")
428
+ word_output = gr.Markdown()
429
+
430
+ def explain_word_handler(word):
431
+ if word:
432
+ return agent.run(f"Explain the word {word}")
433
+ return "Please enter a word to explain."
434
+
435
+ word_btn.click(
436
+ explain_word_handler,
437
+ inputs=[word_input],
438
+ outputs=[word_output]
439
+ )
440
+
441
+ with gr.Tab("Grammar Lessons"):
442
+ with gr.Row():
443
+ grammar_topic = gr.Radio(
444
+ ["Present Tense", "Articles", "Prepositions", "Past Tense"],
445
+ label="Choose a grammar topic"
446
+ )
447
+ grammar_btn = gr.Button("Get Lesson", variant="primary")
448
+ grammar_output = gr.Markdown()
449
+
450
+ def grammar_handler(topic):
451
+ if topic:
452
+ return agent.run(f"Give me a grammar lesson on {topic}")
453
+ return "Please select a grammar topic."
454
+
455
+ grammar_btn.click(
456
+ grammar_handler,
457
+ inputs=[grammar_topic],
458
+ outputs=[grammar_output]
459
+ )
460
+
461
+ with gr.Tab("Practice Exercises"):
462
+ with gr.Row():
463
+ exercise_type = gr.Radio(
464
+ ["Vocabulary", "Grammar", "Sentence Building"],
465
+ label="Choose exercise type"
466
+ )
467
+ exercise_btn = gr.Button("Get Exercise", variant="primary")
468
+ exercise_output = gr.Markdown()
469
+
470
+ def exercise_handler(ex_type):
471
+ if ex_type:
472
+ return agent.run(f"Give me a {ex_type.lower()} practice exercise")
473
+ return "Please select an exercise type."
474
+
475
+ exercise_btn.click(
476
+ exercise_handler,
477
+ inputs=[exercise_type],
478
+ outputs=[exercise_output]
479
+ )
480
+
481
+ with gr.Tab("Free Chat"):
482
+ with gr.Row():
483
+ chat_input = gr.Textbox(
484
+ label="Ask anything about English",
485
+ placeholder="e.g., Explain the word great, Give me grammar lesson"
486
+ )
487
+ chat_btn = gr.Button("Ask", variant="primary")
488
+ chat_output = gr.Markdown()
489
+
490
+ chat_btn.click(
491
+ agent.run,
492
+ inputs=[chat_input],
493
+ outputs=[chat_output]
494
+ )
495
+
496
+ # Show welcome message by default
497
+ demo.load(lambda: agent.run(""), outputs=[chat_output])
498
+
499
+ return demo
500
+
501
+ # Launch the English Tutor
502
+ if __name__ == "__main__":
503
+ demo = create_ui()
504
+ demo.launch()
505
+
506
+ except ImportError:
507
+ print("Gradio not available. Running in console mode.")
508
+ if __name__ == "__main__":
509
+ print("English Tutor AI - Console Mode")
510
+ print("=" * 40)
511
+ print(agent.run(""))
512
+
513
+ while True:
514
+ try:
515
+ user_input = input("\nYou: ")
516
+ if user_input.lower() in ['quit', 'exit', 'bye']:
517
+ print("Goodbye! Keep practicing your English!")
518
+ break
519
+ print("\nTutor:", agent.run(user_input))
520
+ except KeyboardInterrupt:
521
+ print("\nGoodbye! Keep practicing your English!")
522
+ break