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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -291
app.py CHANGED
@@ -1,9 +1,22 @@
1
- from smolagents import CodeAgent, HfApiModel, tool
2
  import yaml
3
  from tools.final_answer import FinalAnswerTool
4
- from Gradio_UI import GradioUI
5
  import random
6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  @tool
8
  def explain_word(word: str) -> str:
9
  """Explains an English word with definition, pronunciation, examples, and usage tips.
@@ -14,7 +27,7 @@ def explain_word(word: str) -> str:
14
  Returns:
15
  A comprehensive explanation of the word
16
  """
17
- # Simple word database for demonstration
18
  word_database = {
19
  "hello": {
20
  "definition": "A greeting used when meeting someone or starting a conversation",
@@ -51,10 +64,46 @@ def explain_word(word: str) -> str:
51
  ],
52
  "synonyms": ["study", "acquire", "master", "understand"],
53
  "usage_tip": "Often followed by 'to' + verb (learn to speak) or 'about' + noun (learn about history)."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54
  }
55
  }
56
 
57
- word_lower = word.lower()
58
 
59
  if word_lower in word_database:
60
  info = word_database[word_lower]
@@ -69,14 +118,14 @@ def explain_word(word: str) -> str:
69
  response += f"**Usage Tip:** {info['usage_tip']}"
70
  return response
71
  else:
72
- return f"I don't have detailed information about '{word}' in my database. However, here's a general explanation:\n\n'{word}' is an English word. To learn more about it, try:\n- Looking it up in a dictionary\n- Using it in sentences\n- Finding synonyms and antonyms\n- Practicing pronunciation\n\nWould you like me to help with grammar rules or suggest other vocabulary words to learn?"
73
 
74
  @tool
75
  def grammar_lesson(topic: str) -> str:
76
  """Provides grammar lessons on various English topics.
77
 
78
  Args:
79
- topic: The grammar topic to explain (tenses, articles, prepositions, etc.)
80
 
81
  Returns:
82
  A detailed grammar lesson with examples
@@ -103,288 +152,4 @@ def grammar_lesson(topic: str) -> str:
103
  "articles": {
104
  "title": "Articles (a, an, the)",
105
  "explanation": "Articles are words that introduce nouns. English has three articles: 'a', 'an', and 'the'.",
106
- "types": [
107
- {
108
- "name": "Indefinite Articles (a, an)",
109
- "form": "'a' before consonant sounds, 'an' before vowel sounds",
110
- "examples": ["a book", "an apple", "a university", "an hour"],
111
- "usage": "For non-specific, countable singular nouns"
112
- },
113
- {
114
- "name": "Definite Article (the)",
115
- "form": "'the' before specific nouns",
116
- "examples": ["the book I'm reading", "the sun", "the United States"],
117
- "usage": "For specific nouns, unique things, or previously mentioned items"
118
- }
119
- ]
120
- },
121
- "prepositions": {
122
- "title": "Prepositions (in, on, at, etc.)",
123
- "explanation": "Prepositions show relationships between words, often indicating time, place, or direction.",
124
- "types": [
125
- {
126
- "name": "Prepositions of Time",
127
- "form": "in, on, at",
128
- "examples": ["in 2023", "on Monday", "at 3 o'clock", "in the morning"],
129
- "usage": "in (months/years), on (days/dates), at (specific times)"
130
- },
131
- {
132
- "name": "Prepositions of Place",
133
- "form": "in, on, at, under, above",
134
- "examples": ["in the house", "on the table", "at school", "under the bed"],
135
- "usage": "Describe where something is located"
136
- }
137
- ]
138
- }
139
- }
140
-
141
- topic_lower = topic.lower().replace(" ", "_")
142
-
143
- if topic_lower in grammar_lessons:
144
- lesson = grammar_lessons[topic_lower]
145
- response = f"## {lesson['title']}\n\n"
146
- response += f"{lesson['explanation']}\n\n"
147
-
148
- for grammar_type in lesson['types']:
149
- response += f"### {grammar_type['name']}\n"
150
- response += f"**Form:** {grammar_type['form']}\n"
151
- response += f"**Usage:** {grammar_type['usage']}\n"
152
- response += f"**Examples:**\n"
153
- for example in grammar_type['examples']:
154
- response += f"- {example}\n"
155
- response += "\n"
156
-
157
- return response
158
- else:
159
- available_topics = list(grammar_lessons.keys())
160
- return f"I don't have a lesson on '{topic}'. Here are available grammar topics:\n\n" + \
161
- "\n".join([f"- {topic.replace('_', ' ').title()}" for topic in available_topics]) + \
162
- "\n\nPlease choose one of these topics for a detailed lesson."
163
-
164
- @tool
165
- def practice_exercise(exercise_type: str) -> str:
166
- """Generates practice exercises for English learning.
167
-
168
- Args:
169
- exercise_type: Type of exercise (vocabulary, grammar, sentence_building)
170
-
171
- Returns:
172
- A practice exercise with questions
173
- """
174
- exercises = {
175
- "vocabulary": [
176
- {
177
- "question": "Choose the correct word to complete the sentence:",
178
- "sentence": "The weather is very _____ today.",
179
- "options": ["beautiful", "beautifully", "beauty", "beautify"],
180
- "correct": "beautiful",
181
- "explanation": "'Beautiful' is an adjective that describes the noun 'weather'."
182
- },
183
- {
184
- "question": "What is the opposite of 'difficult'?",
185
- "options": ["easy", "hard", "complex", "challenging"],
186
- "correct": "easy",
187
- "explanation": "'Easy' is the antonym of 'difficult'."
188
- }
189
- ],
190
- "grammar": [
191
- {
192
- "question": "Choose the correct article:",
193
- "sentence": "I saw _____ elephant at the zoo.",
194
- "options": ["a", "an", "the", "no article"],
195
- "correct": "an",
196
- "explanation": "Use 'an' before words starting with vowel sounds. 'Elephant' starts with 'e'."
197
- },
198
- {
199
- "question": "Select the correct tense:",
200
- "sentence": "She _____ to school every day.",
201
- "options": ["go", "goes", "going", "went"],
202
- "correct": "goes",
203
- "explanation": "For third person singular in simple present, add 's' to the verb."
204
- }
205
- ],
206
- "sentence_building": [
207
- {
208
- "question": "Arrange these words to make a correct sentence:",
209
- "words": ["I", "every", "morning", "coffee", "drink"],
210
- "correct": "I drink coffee every morning.",
211
- "explanation": "Subject + verb + object + time expression is a common sentence pattern."
212
- },
213
- {
214
- "question": "Complete the sentence with the correct word order:",
215
- "sentence": "Yesterday, [beautiful/very/a/saw/I/movie]",
216
- "correct": "Yesterday, I saw a very beautiful movie.",
217
- "explanation": "Time + subject + verb + article + adverb + adjective + noun"
218
- }
219
- ]
220
- }
221
-
222
- if exercise_type in exercises:
223
- exercise = random.choice(exercises[exercise_type])
224
- response = f"## {exercise_type.title()} Practice\n\n"
225
- response += f"**{exercise['question']}**\n\n"
226
-
227
- if 'sentence' in exercise:
228
- response += f"Sentence: {exercise['sentence']}\n\n"
229
-
230
- if 'words' in exercise:
231
- response += f"Words to arrange: {', '.join(exercise['words'])}\n\n"
232
-
233
- if 'options' in exercise:
234
- response += "Options:\n"
235
- for i, option in enumerate(exercise['options'], 1):
236
- response += f"{i}. {option}\n"
237
- response += "\n"
238
-
239
- response += f"**Correct Answer:** {exercise['correct']}\n\n"
240
- response += f"**Explanation:** {exercise['explanation']}"
241
-
242
- return response
243
- else:
244
- return f"Available exercise types: vocabulary, grammar, sentence_building\n\nPlease choose one of these types for practice."
245
-
246
- # Setup agent
247
- final_answer = FinalAnswerTool()
248
-
249
- # Using Mistral model for better English instruction
250
- model = HfApiModel(
251
- max_tokens=2096,
252
- temperature=0.7,
253
- model_id='mistralai/Mistral-7B-Instruct-v0.1',
254
- custom_role_conversions={
255
- "system": "<s>[INST] <<SYS>>\n{message}\n<</SYS>>\n\n",
256
- "human": "{message} [/INST]",
257
- "assistant": "{message} </s><s>[INST] "
258
- },
259
- )
260
-
261
- # Define all required prompt templates
262
- prompt_templates = {
263
- "react-system": """You are an English tutor AI that helps people improve their English skills.
264
- You have access to the following tools:
265
-
266
- {tools_string}
267
-
268
- You should help users with:
269
- 1. Explaining English words (definitions, pronunciation, examples)
270
- 2. Teaching grammar rules and concepts
271
- 3. Providing practice exercises
272
-
273
- Always be encouraging and patient. Explain things clearly with examples.
274
-
275
- To use a tool, output an action in this format:
276
- ```py
277
- action = tool_name(arg1=value1, arg2=value2, ...)
278
- ```
279
-
280
- Always use Python syntax for calling tools. After using a tool, provide additional context or explanation to help the user learn better. Use final_answer to conclude your response.
281
- """,
282
- "react-human": "{input_string}",
283
- "react-assistant": "{agent_response}",
284
- "final_answer": {
285
- "pre_messages": "Here's your English lesson:",
286
- "template": "Final Answer: {answer}",
287
- "post_messages": "Keep practicing! Would you like to learn something else?"
288
- },
289
- "system_prompt": "You are a helpful English tutor that explains words, teaches grammar, and provides practice exercises.",
290
- "planning": {
291
- "pre_messages": "I'll help you improve your English skills.",
292
- "template": "Plan: {planning}",
293
- "post_messages": "Let me provide you with the best English learning experience.",
294
- "initial_plan": "I'll identify what the user wants to learn about English and use the appropriate tools to help them.",
295
- "update_plan_pre_messages": "Let me adjust my teaching approach.",
296
- "update_plan_template": "Updated Plan: {planning}",
297
- "update_plan_post_messages": "Now I'll continue with this updated approach."
298
- },
299
- "managed_agent": {
300
- "pre_messages": "Let me help you with your English learning.",
301
- "template": "{agent_response}",
302
- "post_messages": "I hope this helps improve your English!",
303
- "task": "Help users improve their English skills through word explanations, grammar lessons, and practice exercises.",
304
- "report": "English learning session completed with explanations and practice exercises provided."
305
- }
306
- }
307
-
308
- # Create the agent with all required templates
309
- agent = CodeAgent(
310
- model=model,
311
- tools=[final_answer, explain_word, grammar_lesson, practice_exercise],
312
- max_steps=5,
313
- verbosity_level=1,
314
- prompt_templates=prompt_templates
315
- )
316
-
317
- # Create a custom Gradio UI for English learning
318
- class EnglishTutorUI(GradioUI):
319
- def launch(self, **kwargs):
320
- import gradio as gr
321
-
322
- with gr.Blocks(theme=gr.themes.Soft(), title="English Tutor AI") as demo:
323
- gr.Markdown("# 🇬🇧 English Tutor AI")
324
- gr.Markdown("Improve your English with AI assistance!")
325
-
326
- with gr.Tab("Word Explanation"):
327
- with gr.Row():
328
- word_input = gr.Textbox(
329
- label="Enter an English word",
330
- placeholder="e.g., beautiful, learn, hello"
331
- )
332
- word_btn = gr.Button("Explain Word", variant="primary")
333
- word_output = gr.Markdown()
334
-
335
- word_btn.click(
336
- lambda word: agent.run(f"Explain the word '{word}' with definition, pronunciation, examples, and usage tips"),
337
- inputs=[word_input],
338
- outputs=[word_output]
339
- )
340
-
341
- with gr.Tab("Grammar Lessons"):
342
- with gr.Row():
343
- grammar_topic = gr.Radio(
344
- ["Present Tense", "Articles", "Prepositions"],
345
- label="Choose a grammar topic"
346
- )
347
- grammar_btn = gr.Button("Get Lesson", variant="primary")
348
- grammar_output = gr.Markdown()
349
-
350
- grammar_btn.click(
351
- lambda topic: agent.run(f"Give me a grammar lesson on {topic}"),
352
- inputs=[grammar_topic],
353
- outputs=[grammar_output]
354
- )
355
-
356
- with gr.Tab("Practice Exercises"):
357
- with gr.Row():
358
- exercise_type = gr.Radio(
359
- ["Vocabulary", "Grammar", "Sentence Building"],
360
- label="Choose exercise type"
361
- )
362
- exercise_btn = gr.Button("Get Exercise", variant="primary")
363
- exercise_output = gr.Markdown()
364
-
365
- exercise_btn.click(
366
- lambda ex_type: agent.run(f"Give me a {ex_type.lower()} practice exercise"),
367
- inputs=[exercise_type],
368
- outputs=[exercise_output]
369
- )
370
-
371
- with gr.Tab("Free Chat"):
372
- with gr.Row():
373
- chat_input = gr.Textbox(
374
- label="Ask anything about English",
375
- placeholder="e.g., What's the difference between 'a' and 'an'?"
376
- )
377
- chat_btn = gr.Button("Ask", variant="primary")
378
- chat_output = gr.Markdown()
379
-
380
- chat_btn.click(
381
- lambda question: agent.run(question),
382
- inputs=[chat_input],
383
- outputs=[chat_output]
384
- )
385
-
386
- demo.launch(**kwargs)
387
-
388
- # Launch the English Tutor
389
- if __name__ == "__main__":
390
- EnglishTutorUI(agent).launch()
 
1
+ from smolagents import CodeAgent, tool
2
  import yaml
3
  from tools.final_answer import FinalAnswerTool
 
4
  import random
5
 
6
+ # Mock Model that works without external API calls
7
+ class LocalModel:
8
+ def __init__(self):
9
+ self.max_tokens = 2096
10
+ self.temperature = 0.7
11
+ self.model_id = 'local-model'
12
+
13
+ def generate(self, messages, **kwargs):
14
+ # Simple response generation without external API
15
+ class Response:
16
+ def __init__(self, content):
17
+ self.content = content
18
+ return Response("Using local processing for English tutoring.")
19
+
20
  @tool
21
  def explain_word(word: str) -> str:
22
  """Explains an English word with definition, pronunciation, examples, and usage tips.
 
27
  Returns:
28
  A comprehensive explanation of the word
29
  """
30
+ # Enhanced word database with common English words
31
  word_database = {
32
  "hello": {
33
  "definition": "A greeting used when meeting someone or starting a conversation",
 
64
  ],
65
  "synonyms": ["study", "acquire", "master", "understand"],
66
  "usage_tip": "Often followed by 'to' + verb (learn to speak) or 'about' + noun (learn about history)."
67
+ },
68
+ "great": {
69
+ "definition": "Of an extent, amount, or intensity considerably above average; excellent",
70
+ "pronunciation": "grayt",
71
+ "part_of_speech": "adjective",
72
+ "examples": [
73
+ "She did a great job on the project.",
74
+ "The Great Wall of China is amazing.",
75
+ "Great! Let's start the lesson."
76
+ ],
77
+ "synonyms": ["excellent", "wonderful", "fantastic", "outstanding"],
78
+ "usage_tip": "Can be used to describe size, quality, or as an exclamation of approval."
79
+ },
80
+ "friend": {
81
+ "definition": "A person you know well and regard with affection and trust",
82
+ "pronunciation": "frend",
83
+ "part_of_speech": "noun",
84
+ "examples": [
85
+ "She is my best friend.",
86
+ "I made a new friend at school.",
87
+ "Friends help each other."
88
+ ],
89
+ "synonyms": ["buddy", "pal", "companion", "mate"],
90
+ "usage_tip": "Friends are people you choose to spend time with and share experiences."
91
+ },
92
+ "happy": {
93
+ "definition": "Feeling or showing pleasure or contentment",
94
+ "pronunciation": "HAP-ee",
95
+ "part_of_speech": "adjective",
96
+ "examples": [
97
+ "I'm happy to see you!",
98
+ "The children look happy playing.",
99
+ "Happy birthday to you!"
100
+ ],
101
+ "synonyms": ["joyful", "cheerful", "delighted", "glad"],
102
+ "usage_tip": "Used to describe positive emotions and feelings of joy."
103
  }
104
  }
105
 
106
+ word_lower = word.lower().strip()
107
 
108
  if word_lower in word_database:
109
  info = word_database[word_lower]
 
118
  response += f"**Usage Tip:** {info['usage_tip']}"
119
  return response
120
  else:
121
+ 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?"
122
 
123
  @tool
124
  def grammar_lesson(topic: str) -> str:
125
  """Provides grammar lessons on various English topics.
126
 
127
  Args:
128
+ topic: The grammar topic to explain (present_tense, articles, prepositions, etc.)
129
 
130
  Returns:
131
  A detailed grammar lesson with examples
 
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": [