File size: 5,123 Bytes
6692b4a be4a346 50cb475 be4a346 6692b4a 5d3b9c3 6692b4a be4a346 6692b4a 2cd22a8 6692b4a 5d3b9c3 6692b4a be4a346 6692b4a be4a346 6692b4a be4a346 6692b4a 15edf32 be4a346 6692b4a be4a346 6692b4a be4a346 6692b4a be4a346 6692b4a be4a346 6692b4a be4a346 6692b4a be4a346 6692b4a be4a346 6692b4a be4a346 | 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 | import os
from dotenv import load_dotenv
import gradio as gr
from groq import Groq
load_dotenv()
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
def chatbot_response(user_input, action, language, conversation_history, name, proficiency_level):
if not client:
error_msg = "⚠️ Error: Missing GROQ_API_KEY. Please check your .env file."
conversation_history.append((user_input, error_msg))
return conversation_history
system_message = f"""You are a {language} tutor for {name or 'a student'} ({proficiency_level} level).
Provide personalized, level-appropriate responses. Use their name occasionally. If the user doesn't enter their name don't use it.
For games, maintain context until completion. Acknowledge different dialects where relevant.
**Important**: The user is communicating via text - focus on written errors.
Only provide pronunciation help if explicitly requested.
When correcting errors:
1. Clearly indicate the error with 🚨Error Alret🚨
2. Explain why it's incorrect
3. Provide the correct version
4. Offer a brief practice example"""
if action == "vocabulary":
user_message = f"Provide 5 {language} vocabulary words for {proficiency_level} learners."
elif action == "grammar":
user_message = f"Explain a {language} grammar concept suitable for {proficiency_level} learners."
elif action == "conversation":
user_message = f"Start a {language} conversation practice. First offer 3 topic choices."
elif action == "game":
user_message = f"Create an interactive {language} language game for {proficiency_level} learners. Maintain game context."
else:
user_message = user_input
conversation_history.append((user_message, ""))
try:
messages = [{"role": "system", "content": system_message}]
for msg, response in conversation_history:
messages.append({"role": "user", "content": msg})
if response:
messages.append({"role": "assistant", "content": response.replace(f"**{language} Tutor:** ", "")})
completion = client.chat.completions.create(
model="llama-3.3-70b-versatile",
messages=messages,
temperature=0.7,
max_tokens=2000,
stream=True,
)
chatbot_message = ""
for chunk in completion:
if chunk.choices[0].delta.content:
chatbot_message += chunk.choices[0].delta.content
conversation_history[-1] = (user_message, f"**{language} Tutor:** {chatbot_message}")
yield conversation_history
except Exception as e:
error_msg = f"⚠️ Error: {str(e)}. Please try again or reload."
conversation_history[-1] = (user_message, f"**{language} Tutor:** {error_msg}")
yield conversation_history
def clear_chat():
return [], []
with gr.Blocks(theme=gr.themes.Default(primary_hue="green")) as demo:
gr.Markdown("# 🌍 Multi-Language Learning Buddy")
gr.Markdown("Welcome! Practice vocabulary, grammar, conversation, and play language games in multiple languages.")
with gr.Row():
language = gr.Dropdown(["French", "Spanish", "German", "Italian", "Portuguese"], label="Language", value="French")
proficiency = gr.Dropdown(["Beginner", "Intermediate", "Advanced"], label="Your Level", value="Beginner")
name = gr.Textbox(label="Your Name", placeholder="Enter your name...")
chatbot = gr.Chatbot(height=500)
conversation_history = gr.State([])
with gr.Row():
user_input = gr.Textbox(placeholder="Type here or choose an activity below...", show_label=False)
send_btn = gr.Button("Send", variant="primary")
with gr.Row():
vocab_btn = gr.Button("📚 Daily Vocabulary")
grammar_btn = gr.Button("📖 Grammar Lesson")
conv_btn = gr.Button("💬 Practice Conversation")
game_btn = gr.Button("🎮 Language Game")
clear_btn = gr.Button("🔄 Clear Chat")
input_components = [user_input, gr.State("chat"), language, conversation_history, name, proficiency]
send_btn.click(
chatbot_response, inputs=input_components, outputs=chatbot
).then(lambda: "", None, user_input)
user_input.submit(
chatbot_response, inputs=input_components, outputs=chatbot
).then(lambda: "", None, user_input)
action_btns = [vocab_btn, grammar_btn, conv_btn, game_btn]
for btn, action in zip(action_btns, ["vocabulary", "grammar", "conversation", "game"]):
btn.click(
chatbot_response,
inputs=[gr.State(""), gr.State(action)] + input_components[2:],
outputs=chatbot
)
clear_btn.click(
clear_chat,
outputs=[chatbot, conversation_history],
)
if __name__ == "__main__":
if not GROQ_API_KEY:
print("❌ Error: GROQ_API_KEY missing. Create a .env file with your key.")
else:
demo.launch() |