Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -26,6 +26,139 @@ TTS_CLIENT = Client("KindSynapse/Youssef-Ahmed-Private-Text-To-Speech-Unlimited"
|
|
| 26 |
# إعداد محرك تحويل الكلام لنص
|
| 27 |
recognizer = sr.Recognizer()
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
def convert_audio_to_text(audio_path):
|
| 30 |
"""تحويل الصوت إلى نص"""
|
| 31 |
try:
|
|
@@ -44,32 +177,6 @@ def convert_audio_to_text(audio_path):
|
|
| 44 |
print(f"Error in speech recognition: {str(e)}")
|
| 45 |
return None
|
| 46 |
|
| 47 |
-
def get_bot_response(message):
|
| 48 |
-
"""الحصول على رد من البوت"""
|
| 49 |
-
try:
|
| 50 |
-
response = requests.post(
|
| 51 |
-
"https://api.deepseek.com/v1/chat/completions",
|
| 52 |
-
headers={"Authorization": f"Bearer {API_KEY}"},
|
| 53 |
-
json={
|
| 54 |
-
"model": "deepseek-chat",
|
| 55 |
-
"messages": [
|
| 56 |
-
{
|
| 57 |
-
"role": "system",
|
| 58 |
-
"content": "You are Sam, a friendly English tutor. Keep responses short and encouraging."
|
| 59 |
-
},
|
| 60 |
-
{
|
| 61 |
-
"role": "user",
|
| 62 |
-
"content": message
|
| 63 |
-
}
|
| 64 |
-
],
|
| 65 |
-
"temperature": 0.7
|
| 66 |
-
}
|
| 67 |
-
)
|
| 68 |
-
return response.json()["choices"][0]["message"]["content"]
|
| 69 |
-
except Exception as e:
|
| 70 |
-
print(f"Error getting bot response: {str(e)}")
|
| 71 |
-
return "Sorry, I couldn't process that. Could you try again?"
|
| 72 |
-
|
| 73 |
def text_to_speech(text):
|
| 74 |
"""تحويل النص إلى صوت"""
|
| 75 |
try:
|
|
@@ -87,9 +194,18 @@ def text_to_speech(text):
|
|
| 87 |
print(f"Error in text to speech: {str(e)}")
|
| 88 |
return None
|
| 89 |
|
|
|
|
|
|
|
|
|
|
| 90 |
def chat_function(audio, history):
|
| 91 |
"""الدالة الرئيسية للمحادثة"""
|
| 92 |
try:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
# إذا لم يكن هناك صوت، نرجع بدون تغيير
|
| 94 |
if audio is None:
|
| 95 |
return history, None
|
|
@@ -100,7 +216,7 @@ def chat_function(audio, history):
|
|
| 100 |
return history, None
|
| 101 |
|
| 102 |
# الحصول على رد البوت
|
| 103 |
-
bot_response = get_bot_response(user_message)
|
| 104 |
|
| 105 |
# تحويل رد البوت إلى صوت
|
| 106 |
audio_response = text_to_speech(bot_response)
|
|
@@ -115,19 +231,26 @@ def chat_function(audio, history):
|
|
| 115 |
return history, None
|
| 116 |
|
| 117 |
# إنشاء واجهة المستخدم
|
| 118 |
-
with gr.Blocks() as demo:
|
| 119 |
-
gr.Markdown("# 🎓 English
|
|
|
|
| 120 |
|
| 121 |
-
chatbot = gr.Chatbot(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 122 |
|
| 123 |
with gr.Row():
|
| 124 |
audio_input = gr.Audio(
|
| 125 |
label="Your Voice",
|
| 126 |
-
type="filepath"
|
|
|
|
| 127 |
)
|
| 128 |
audio_output = gr.Audio(
|
| 129 |
label="Tutor's Voice",
|
| 130 |
-
type="filepath"
|
|
|
|
| 131 |
)
|
| 132 |
|
| 133 |
# ربط الأحداث
|
|
@@ -139,4 +262,4 @@ with gr.Blocks() as demo:
|
|
| 139 |
|
| 140 |
# تشغيل التطبيق
|
| 141 |
if __name__ == "__main__":
|
| 142 |
-
demo.launch(
|
|
|
|
| 26 |
# إعداد محرك تحويل الكلام لنص
|
| 27 |
recognizer = sr.Recognizer()
|
| 28 |
|
| 29 |
+
# البرومبت الرئيسي
|
| 30 |
+
MAIN_SYSTEM_PROMPT = {
|
| 31 |
+
"role": "system",
|
| 32 |
+
"content": """You are Sam, an intelligent and adaptive English tutor. Your responses must be in JSON format with these keys:
|
| 33 |
+
'response': Your main response,
|
| 34 |
+
'corrections': Grammar or pronunciation corrections if needed,
|
| 35 |
+
'vocabulary': Suggested alternative words or phrases,
|
| 36 |
+
'level_assessment': Current assessment of user's English level (beginner/intermediate/advanced),
|
| 37 |
+
'encouragement': A motivating comment,
|
| 38 |
+
'context_memory': Important details about the user to remember (interests, job, etc.)
|
| 39 |
+
|
| 40 |
+
Guidelines:
|
| 41 |
+
1. Maintain natural conversation while gathering user information
|
| 42 |
+
2. Adapt language complexity to user's level
|
| 43 |
+
3. Provide gentle corrections without interrupting flow
|
| 44 |
+
4. Remember and use context from previous messages
|
| 45 |
+
5. Focus on user's interests and profession
|
| 46 |
+
6. Give specific vocabulary related to user's field
|
| 47 |
+
7. Keep responses encouraging and supportive
|
| 48 |
+
|
| 49 |
+
Special behaviors:
|
| 50 |
+
- If user mentions their country → Ask about their culture/country
|
| 51 |
+
- If user mentions their job → Use profession-specific vocabulary
|
| 52 |
+
- If user mentions hobbies → Engage in that topic
|
| 53 |
+
- For beginners → Use simple words and short sentences
|
| 54 |
+
- For intermediate/advanced → Introduce more complex vocabulary
|
| 55 |
+
|
| 56 |
+
Always maintain conversation history and adapt based on it."""
|
| 57 |
+
}
|
| 58 |
+
|
| 59 |
+
# برومبت الترحيب
|
| 60 |
+
WELCOME_PROMPT = {
|
| 61 |
+
"role": "system",
|
| 62 |
+
"content": """Create a warm welcome message that:
|
| 63 |
+
1. Introduces you as Sam, the English tutor
|
| 64 |
+
2. Asks for the user's name
|
| 65 |
+
3. Asks about their background (country, job/studies)
|
| 66 |
+
4. Inquires about their English learning goals
|
| 67 |
+
|
| 68 |
+
Return in JSON format with key 'greeting'.
|
| 69 |
+
Keep it friendly and encouraging."""
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
class EnglishTutor:
|
| 73 |
+
def __init__(self):
|
| 74 |
+
self.chat_history = [MAIN_SYSTEM_PROMPT]
|
| 75 |
+
self.user_info = {
|
| 76 |
+
"name": None,
|
| 77 |
+
"level": None,
|
| 78 |
+
"interests": [],
|
| 79 |
+
"country": None,
|
| 80 |
+
"profession": None,
|
| 81 |
+
"goals": None
|
| 82 |
+
}
|
| 83 |
+
self.is_first_interaction = True
|
| 84 |
+
|
| 85 |
+
def get_welcome_message(self):
|
| 86 |
+
"""توليد رسالة ترحيب"""
|
| 87 |
+
try:
|
| 88 |
+
response = requests.post(
|
| 89 |
+
"https://api.deepseek.com/v1/chat/completions",
|
| 90 |
+
headers={"Authorization": f"Bearer {API_KEY}"},
|
| 91 |
+
json={
|
| 92 |
+
"model": "deepseek-chat",
|
| 93 |
+
"messages": [WELCOME_PROMPT],
|
| 94 |
+
"temperature": random.uniform(0.7, 0.9),
|
| 95 |
+
"response_format": {"type": "json_object"}
|
| 96 |
+
}
|
| 97 |
+
)
|
| 98 |
+
welcome_json = json.loads(response.json()["choices"][0]["message"]["content"])
|
| 99 |
+
return welcome_json["greeting"]
|
| 100 |
+
except Exception as e:
|
| 101 |
+
print(f"Error in welcome message: {str(e)}")
|
| 102 |
+
return "Hi! I'm Sam, your English tutor. What's your name?"
|
| 103 |
+
|
| 104 |
+
def get_bot_response(self, user_message):
|
| 105 |
+
"""الحصول على رد من البوت"""
|
| 106 |
+
try:
|
| 107 |
+
# إضافة رسالة المستخدم للمحادثة
|
| 108 |
+
self.chat_history.append({"role": "user", "content": user_message})
|
| 109 |
+
|
| 110 |
+
response = requests.post(
|
| 111 |
+
"https://api.deepseek.com/v1/chat/completions",
|
| 112 |
+
headers={"Authorization": f"Bearer {API_KEY}"},
|
| 113 |
+
json={
|
| 114 |
+
"model": "deepseek-chat",
|
| 115 |
+
"messages": self.chat_history,
|
| 116 |
+
"temperature": random.uniform(0.9, 1.0),
|
| 117 |
+
"response_format": {"type": "json_object"}
|
| 118 |
+
}
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
bot_response = json.loads(response.json()["choices"][0]["message"]["content"])
|
| 122 |
+
|
| 123 |
+
# تحديث معلومات المستخدم
|
| 124 |
+
if "level_assessment" in bot_response:
|
| 125 |
+
self.user_info["level"] = bot_response["level_assessment"]
|
| 126 |
+
if "context_memory" in bot_response:
|
| 127 |
+
self._update_user_info(bot_response["context_memory"])
|
| 128 |
+
|
| 129 |
+
# تنسيق الرد
|
| 130 |
+
formatted_response = self._format_response(bot_response)
|
| 131 |
+
|
| 132 |
+
# إضافة رد البوت للمحادثة
|
| 133 |
+
self.chat_history.append({"role": "assistant", "content": json.dumps(bot_response)})
|
| 134 |
+
|
| 135 |
+
return formatted_response
|
| 136 |
+
except Exception as e:
|
| 137 |
+
print(f"Error getting bot response: {str(e)}")
|
| 138 |
+
return "I apologize, but I couldn't process that properly. Could you try again?"
|
| 139 |
+
|
| 140 |
+
def _update_user_info(self, context_memory):
|
| 141 |
+
"""تحديث معلومات المستخدم من الذاكرة السياقية"""
|
| 142 |
+
if isinstance(context_memory, dict):
|
| 143 |
+
for key in self.user_info:
|
| 144 |
+
if key in context_memory:
|
| 145 |
+
self.user_info[key] = context_memory[key]
|
| 146 |
+
|
| 147 |
+
def _format_response(self, response_dict):
|
| 148 |
+
"""تنسيق الرد بشكل جميل"""
|
| 149 |
+
formatted = response_dict["response"]
|
| 150 |
+
|
| 151 |
+
if response_dict.get("corrections"):
|
| 152 |
+
formatted += f"\n\n✍️ Corrections: {response_dict['corrections']}"
|
| 153 |
+
|
| 154 |
+
if response_dict.get("vocabulary"):
|
| 155 |
+
formatted += f"\n\n📚 Vocabulary: {response_dict['vocabulary']}"
|
| 156 |
+
|
| 157 |
+
if response_dict.get("encouragement"):
|
| 158 |
+
formatted += f"\n\n🌟 {response_dict['encouragement']}"
|
| 159 |
+
|
| 160 |
+
return formatted
|
| 161 |
+
|
| 162 |
def convert_audio_to_text(audio_path):
|
| 163 |
"""تحويل الصوت إلى نص"""
|
| 164 |
try:
|
|
|
|
| 177 |
print(f"Error in speech recognition: {str(e)}")
|
| 178 |
return None
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
def text_to_speech(text):
|
| 181 |
"""تحويل النص إلى صوت"""
|
| 182 |
try:
|
|
|
|
| 194 |
print(f"Error in text to speech: {str(e)}")
|
| 195 |
return None
|
| 196 |
|
| 197 |
+
# إنشاء كائن المعلم
|
| 198 |
+
tutor = EnglishTutor()
|
| 199 |
+
|
| 200 |
def chat_function(audio, history):
|
| 201 |
"""الدالة الرئيسية للمحادثة"""
|
| 202 |
try:
|
| 203 |
+
# إذا كانت أول محادثة، نعرض رسالة الترحيب
|
| 204 |
+
if not history:
|
| 205 |
+
welcome = tutor.get_welcome_message()
|
| 206 |
+
welcome_audio = text_to_speech(welcome)
|
| 207 |
+
return [(None, welcome)], welcome_audio
|
| 208 |
+
|
| 209 |
# إذا لم يكن هناك صوت، نرجع بدون تغيير
|
| 210 |
if audio is None:
|
| 211 |
return history, None
|
|
|
|
| 216 |
return history, None
|
| 217 |
|
| 218 |
# الحصول على رد البوت
|
| 219 |
+
bot_response = tutor.get_bot_response(user_message)
|
| 220 |
|
| 221 |
# تحويل رد البوت إلى صوت
|
| 222 |
audio_response = text_to_speech(bot_response)
|
|
|
|
| 231 |
return history, None
|
| 232 |
|
| 233 |
# إنشاء واجهة المستخدم
|
| 234 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
| 235 |
+
gr.Markdown("# 🎓 English Learning Assistant")
|
| 236 |
+
gr.Markdown("Speak naturally and I'll help you improve your English!")
|
| 237 |
|
| 238 |
+
chatbot = gr.Chatbot(
|
| 239 |
+
height=400,
|
| 240 |
+
bubble_full_width=False,
|
| 241 |
+
show_label=False
|
| 242 |
+
)
|
| 243 |
|
| 244 |
with gr.Row():
|
| 245 |
audio_input = gr.Audio(
|
| 246 |
label="Your Voice",
|
| 247 |
+
type="filepath",
|
| 248 |
+
show_label=True
|
| 249 |
)
|
| 250 |
audio_output = gr.Audio(
|
| 251 |
label="Tutor's Voice",
|
| 252 |
+
type="filepath",
|
| 253 |
+
show_label=True
|
| 254 |
)
|
| 255 |
|
| 256 |
# ربط الأحداث
|
|
|
|
| 262 |
|
| 263 |
# تشغيل التطبيق
|
| 264 |
if __name__ == "__main__":
|
| 265 |
+
demo.launch()
|