Blazingg commited on
Commit
be4a346
·
verified ·
1 Parent(s): 6692b4a

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +93 -92
app.py CHANGED
@@ -1,5 +1,4 @@
1
  import os
2
- import time
3
  from dotenv import load_dotenv
4
  import gradio as gr
5
  from groq import Groq
@@ -7,118 +6,120 @@ from groq import Groq
7
  load_dotenv()
8
 
9
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
10
- if not GROQ_API_KEY:
11
- raise ValueError("GROQ_API_KEY not found in .env file or environment variables.")
12
-
13
- client = Groq(api_key=GROQ_API_KEY)
14
-
15
- def chatbot_response(user_input, action, language, conversation_history):
16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
17
  if action == "vocabulary":
18
- prompt = f"Act as a {language} language tutor. Provide 5 vocabulary words for a beginner learning {language} for travel."
19
- action_text = "**Get Daily Vocabulary**"
20
  elif action == "grammar":
21
- prompt = f"Act as a {language} language tutor. Provide a mini-lesson on grammar rules (e.g., verb conjugations, sentence structure)."
22
- action_text = "**Grammar Lesson**"
23
  elif action == "conversation":
24
- prompt = f"Act as a {language} language tutor. Simulate a real-life conversation (e.g., ordering food, asking for directions)."
25
- action_text = "**Practice Conversation**"
26
  elif action == "game":
27
- prompt = f"Act as a {language} language tutor. Create a language game like word matching, fill-in-the-blank, or word puzzles."
28
- action_text = "**Play a Language Game**"
29
  else:
30
- prompt = f"Act as a {language} language tutor. Respond to the following user input: {user_input}"
31
- action_text = ""
32
-
33
-
34
- if action != "chat":
35
- conversation_history.append((f"User selected: {action_text}", ""))
36
- elif user_input.strip():
37
- conversation_history.append((user_input, ""))
38
 
 
 
39
  try:
 
 
 
 
 
 
40
  completion = client.chat.completions.create(
41
- model="llama-3.3-70b-versatile",
42
- messages=[
43
- {"role": "system", "content": "You are a helpful and knowledgeable language tutor."},
44
- {"role": "user", "content": prompt}
45
- ],
46
- temperature=0.8,
47
- max_tokens=2000,
48
- stream=True,
49
  )
50
 
51
-
52
  chatbot_message = ""
53
  for chunk in completion:
54
  if chunk.choices[0].delta.content:
55
  chatbot_message += chunk.choices[0].delta.content
56
- if action != "chat":
57
- conversation_history[-1] = (f"User selected: {action_text}", f"**{language} Tutor:** {chatbot_message}")
58
- else:
59
- conversation_history[-1] = (user_input, f"**{language} Tutor:** {chatbot_message}")
60
- yield conversation_history
61
-
62
 
63
  except Exception as e:
64
- chatbot_message = f"Sorry, an error occurred: {str(e)}. Please try again later."
65
- if action != "chat":
66
- conversation_history[-1] = (f"User selected: {action_text}", f"**{language} Tutor:** {chatbot_message}")
67
- else:
68
- conversation_history[-1] = (user_input, f"**{language} Tutor:** {chatbot_message}")
69
- yield conversation_history
70
 
71
-
72
- with gr.Blocks(theme=gr.themes.Default(primary_hue="green", secondary_hue="gray")) as demo:
73
- gr.Markdown("# Multi-Language Learning Buddy")
74
- gr.Markdown("Welcome! Practice vocabulary, grammar, conversation, and play language games in multiple languages.")
75
 
76
- language = gr.Dropdown(choices=["French", "Spanish", "German", "Italian"], label="Select Language", value="French")
77
-
78
- chatbot = gr.Chatbot(label="Chat with the Language Learning Buddy")
79
- user_input = gr.Textbox(label="Your Message", placeholder="Type your question or response here...", lines=2)
80
- send_button = gr.Button("Send")
81
 
 
82
  with gr.Row():
83
- vocab_button = gr.Button("Get Daily Vocabulary")
84
- grammar_button = gr.Button("Grammar Lesson")
85
- conv_button = gr.Button("Practice Conversation")
86
- game_button = gr.Button("Play a Language Game")
87
-
88
- # Store conversation history
89
  conversation_history = gr.State([])
90
-
91
- # Define button actions
92
- vocab_button.click(
93
- fn=chatbot_response,
94
- inputs=[user_input, gr.State("vocabulary"), language, conversation_history],
95
- outputs=chatbot
96
- )
97
- grammar_button.click(
98
- fn=chatbot_response,
99
- inputs=[user_input, gr.State("grammar"), language, conversation_history],
100
- outputs=chatbot
101
- )
102
- conv_button.click(
103
- fn=chatbot_response,
104
- inputs=[user_input, gr.State("conversation"), language, conversation_history],
105
- outputs=chatbot
106
- )
107
- game_button.click(
108
- fn=chatbot_response,
109
- inputs=[user_input, gr.State("game"), language, conversation_history],
110
- outputs=chatbot
111
- )
112
-
113
- send_button.click(
114
- fn=chatbot_response,
115
- inputs=[user_input, gr.State("chat"), language, conversation_history],
116
- outputs=chatbot
117
- ).then(
118
- lambda: "",
119
- inputs=None,
120
- outputs=user_input
 
 
121
  )
122
 
123
- # Launch the interface
124
- demo.launch()
 
 
 
 
1
  import os
 
2
  from dotenv import load_dotenv
3
  import gradio as gr
4
  from groq import Groq
 
6
  load_dotenv()
7
 
8
  GROQ_API_KEY = os.getenv("GROQ_API_KEY")
 
 
 
 
 
 
9
 
10
+ client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
11
+
12
+ def chatbot_response(user_input, action, language, conversation_history, name, proficiency_level):
13
+ if not client:
14
+ error_msg = "⚠️ Error: Missing GROQ_API_KEY. Please check your .env file."
15
+ conversation_history.append((user_input, error_msg))
16
+ return conversation_history
17
+
18
+ system_message = f"""You are a {language} tutor for {name or 'a student'} ({proficiency_level} level).
19
+ Provide personalized, level-appropriate responses. Use their name occasionally.
20
+ For games, maintain context until completion. Acknowledge different dialects where relevant.
21
+
22
+ **Important**: The user is communicating via text - focus on written errors.
23
+ Only provide pronunciation help if explicitly requested.
24
+
25
+ When correcting errors:
26
+ 1. Clearly indicate the error with 🚨Error Alret🚨
27
+ 2. Explain why it's incorrect
28
+ 3. Provide the correct version
29
+ 4. Offer a brief practice example"""
30
+
31
  if action == "vocabulary":
32
+ user_message = f"Provide 5 {language} vocabulary words for {proficiency_level} travelers."
 
33
  elif action == "grammar":
34
+ user_message = f"Explain a {language} grammar concept suitable for {proficiency_level} learners."
 
35
  elif action == "conversation":
36
+ user_message = f"Start a {language} conversation practice. First offer 3 topic choices and 4th option that offers another 3 options."
 
37
  elif action == "game":
38
+ user_message = f"Create an interactive {language} language game. Maintain game context."
 
39
  else:
40
+ user_message = user_input
 
 
 
 
 
 
 
41
 
42
+ conversation_history.append((user_message, ""))
43
+
44
  try:
45
+ messages = [{"role": "system", "content": system_message}]
46
+ for msg, response in conversation_history:
47
+ messages.append({"role": "user", "content": msg})
48
+ if response:
49
+ messages.append({"role": "assistant", "content": response.replace(f"**{language} Tutor:** ", "")})
50
+
51
  completion = client.chat.completions.create(
52
+ model="llama3-70b-8192",
53
+ messages=messages,
54
+ temperature=0.7,
55
+ max_tokens=2000,
56
+ stream=True,
 
 
 
57
  )
58
 
 
59
  chatbot_message = ""
60
  for chunk in completion:
61
  if chunk.choices[0].delta.content:
62
  chatbot_message += chunk.choices[0].delta.content
63
+ conversation_history[-1] = (user_message, f"**{language} Tutor:** {chatbot_message}")
64
+ yield conversation_history
 
 
 
 
65
 
66
  except Exception as e:
67
+ error_msg = f"⚠️ Error: {str(e)}. Please try again or reload."
68
+ conversation_history[-1] = (user_message, f"**{language} Tutor:** {error_msg}")
69
+ yield conversation_history
 
 
 
70
 
71
+ def clear_chat():
72
+ return [], []
 
 
73
 
74
+ with gr.Blocks(theme=gr.themes.Default(primary_hue="green")) as demo:
75
+ gr.Markdown("# 🌍 Multi-Language Learning Buddy")
76
+ gr.Markdown("Welcome! Practice vocabulary, grammar, conversation, and play language games in multiple languages.")
 
 
77
 
78
+
79
  with gr.Row():
80
+ language = gr.Dropdown(["French", "Spanish", "German", "Italian", "Portuguese"], label="Language", value="French")
81
+ proficiency = gr.Dropdown(["Beginner", "Intermediate", "Advanced"], label="Your Level", value="Beginner")
82
+ name = gr.Textbox(label="Your Name", placeholder="Enter your name...")
83
+
84
+ chatbot = gr.Chatbot(height=500)
 
85
  conversation_history = gr.State([])
86
+
87
+ with gr.Row():
88
+ user_input = gr.Textbox(placeholder="Type here or choose an activity below...", show_label=False)
89
+ send_btn = gr.Button("Send", variant="primary")
90
+
91
+ with gr.Row():
92
+ vocab_btn = gr.Button("📚 Daily Vocabulary")
93
+ grammar_btn = gr.Button("📖 Grammar Lesson")
94
+ conv_btn = gr.Button("💬 Practice Conversation")
95
+ game_btn = gr.Button("🎮 Language Game")
96
+ clear_btn = gr.Button("🔄 Clear Chat")
97
+
98
+ input_components = [user_input, gr.State("chat"), language, conversation_history, name, proficiency]
99
+
100
+ send_btn.click(
101
+ chatbot_response, inputs=input_components, outputs=chatbot
102
+ ).then(lambda: "", None, user_input)
103
+
104
+ user_input.submit(
105
+ chatbot_response, inputs=input_components, outputs=chatbot
106
+ ).then(lambda: "", None, user_input)
107
+
108
+ action_btns = [vocab_btn, grammar_btn, conv_btn, game_btn]
109
+ for btn, action in zip(action_btns, ["vocabulary", "grammar", "conversation", "game"]):
110
+ btn.click(
111
+ chatbot_response,
112
+ inputs=[gr.State(""), gr.State(action)] + input_components[2:],
113
+ outputs=chatbot
114
+ )
115
+
116
+ clear_btn.click(
117
+ clear_chat,
118
+ outputs=[chatbot, conversation_history],
119
  )
120
 
121
+ if __name__ == "__main__":
122
+ if not GROQ_API_KEY:
123
+ print("❌ Error: GROQ_API_KEY missing. Create a .env file with your key.")
124
+ else:
125
+ demo.launch()