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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import requests
|
| 2 |
+
import json
|
| 3 |
+
import random
|
| 4 |
+
from gradio_client import Client
|
| 5 |
+
from dotenv import load_dotenv
|
| 6 |
+
import os
|
| 7 |
+
|
| 8 |
+
# Load environment variables
|
| 9 |
+
load_dotenv()
|
| 10 |
+
|
| 11 |
+
# إعدادات API
|
| 12 |
+
API_URL = "https://api.deepseek.com/v1/chat/completions"
|
| 13 |
+
API_KEY = os.getenv("DEEPSEEK_API_KEY")
|
| 14 |
+
HF_TOKEN = os.getenv("HUGGINGFACE_TOKEN")
|
| 15 |
+
|
| 16 |
+
# إعداد TTS
|
| 17 |
+
TTS_MODEL = os.getenv("TTS_MODEL", "KindSynapse/Youssef-Ahmed-Private-Text-To-Speech-Unlimited")
|
| 18 |
+
TTS_CLIENT = Client(TTS_MODEL, hf_token=HF_TOKEN)
|
| 19 |
+
TTS_PASSWORD = os.getenv("TTS_PASSWORD")
|
| 20 |
+
TTS_VOICE = os.getenv("TTS_VOICE", "coral")
|
| 21 |
+
TTS_SEED = int(os.getenv("TTS_SEED", "12345"))
|
| 22 |
+
|
| 23 |
+
# التحقق من وجود المتغيرات المطلوبة
|
| 24 |
+
required_env_vars = {
|
| 25 |
+
"DEEPSEEK_API_KEY": API_KEY,
|
| 26 |
+
"HUGGINGFACE_TOKEN": HF_TOKEN,
|
| 27 |
+
"TTS_PASSWORD": TTS_PASSWORD
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
for var_name, var_value in required_env_vars.items():
|
| 31 |
+
if not var_value:
|
| 32 |
+
raise ValueError(f"Missing required environment variable: {var_name}")
|
| 33 |
+
|
| 34 |
+
# البرومبت الرئيسي للشات بوت
|
| 35 |
+
MAIN_SYSTEM_PROMPT = {
|
| 36 |
+
"role": "system",
|
| 37 |
+
"content": (
|
| 38 |
+
"You are Sam, a friendly and encouraging English conversation tutor. "
|
| 39 |
+
"Your responses must be in JSON with these keys: "
|
| 40 |
+
"'response': Your main response to the user, "
|
| 41 |
+
"'corrections': Grammar or pronunciation corrections if needed, "
|
| 42 |
+
"'vocabulary': Suggested alternative words or phrases, "
|
| 43 |
+
"'level': Assessment of user's English level (beginner/intermediate/advanced), "
|
| 44 |
+
"'encouragement': A motivating comment. "
|
| 45 |
+
"\n\nGuidelines:"
|
| 46 |
+
"\n1. Adapt your language to their level"
|
| 47 |
+
"\n2. Keep conversations natural and engaging"
|
| 48 |
+
"\n3. Focus on their interests and context"
|
| 49 |
+
"\n4. Be patient and supportive"
|
| 50 |
+
"\n5. Provide gentle corrections"
|
| 51 |
+
"\n6. Suggest vocabulary improvements naturally"
|
| 52 |
+
"\n7. Keep responses clear and structured"
|
| 53 |
+
)
|
| 54 |
+
}
|
| 55 |
+
|
| 56 |
+
# برومبت خاص بالترحيب (مختصر)
|
| 57 |
+
WELCOME_SYSTEM_PROMPT = {
|
| 58 |
+
"role": "system",
|
| 59 |
+
"content": (
|
| 60 |
+
"You are Sam, a friendly English tutor. Create a short, warm welcome message (2-3 sentences max) that: "
|
| 61 |
+
"1) Introduces yourself briefly "
|
| 62 |
+
"2) Asks for the user's name and what they'd like to practice. "
|
| 63 |
+
"Make it casual and friendly. Return ONLY the greeting in JSON format with a single key 'greeting'."
|
| 64 |
+
"Example: {'greeting': 'Hi! I'm Sam, your English buddy. What's your name and what would you like to practice today? 😊'}"
|
| 65 |
+
)
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
class EnglishTutor:
|
| 69 |
+
def __init__(self):
|
| 70 |
+
self.chat_history = []
|
| 71 |
+
self.user_info = {
|
| 72 |
+
"name": None,
|
| 73 |
+
"level": None,
|
| 74 |
+
"interests": None,
|
| 75 |
+
"goals": None
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
def get_welcome_message(self):
|
| 79 |
+
"""توليد رسالة ترحيب فريدة"""
|
| 80 |
+
response = requests.post(
|
| 81 |
+
API_URL,
|
| 82 |
+
headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
|
| 83 |
+
json={
|
| 84 |
+
"model": "deepseek-chat",
|
| 85 |
+
"messages": [WELCOME_SYSTEM_PROMPT],
|
| 86 |
+
"temperature": random.uniform(0.9, 1), # خفضنا التنوع قليلاً للرسائل القصيرة
|
| 87 |
+
"response_format": {"type": "json_object"}
|
| 88 |
+
}
|
| 89 |
+
)
|
| 90 |
+
welcome_json = json.loads(response.json()["choices"][0]["message"]["content"])
|
| 91 |
+
self.chat_history = [MAIN_SYSTEM_PROMPT] # بدء المحادثة بالبرومبت الرئيسي
|
| 92 |
+
return welcome_json["greeting"]
|
| 93 |
+
|
| 94 |
+
def get_bot_response(self, user_message):
|
| 95 |
+
"""معالجة رسالة المستخدم والحصول على رد"""
|
| 96 |
+
self.chat_history.append({"role": "user", "content": user_message})
|
| 97 |
+
|
| 98 |
+
response = requests.post(
|
| 99 |
+
API_URL,
|
| 100 |
+
headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
|
| 101 |
+
json={
|
| 102 |
+
"model": "deepseek-chat",
|
| 103 |
+
"messages": self.chat_history,
|
| 104 |
+
"temperature": random.uniform(0.9, 1.0),
|
| 105 |
+
"response_format": {"type": "json_object"}
|
| 106 |
+
}
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
bot_message = response.json()["choices"][0]["message"]["content"]
|
| 110 |
+
bot_json = json.loads(bot_message)
|
| 111 |
+
|
| 112 |
+
# تحديث معلومات المستخدم إذا وجدت
|
| 113 |
+
if "level" in bot_json:
|
| 114 |
+
self.user_info["level"] = bot_json["level"]
|
| 115 |
+
|
| 116 |
+
self.chat_history.append({"role": "assistant", "content": bot_message})
|
| 117 |
+
return bot_json
|
| 118 |
+
|
| 119 |
+
def text_to_speech(self, text):
|
| 120 |
+
"""تحويل نص إلى صوت مع مراعاة المبتدئين في اللغة الإنجليزية"""
|
| 121 |
+
# تنظيف النص من أي علامات إضافية أو نصوص زائدة
|
| 122 |
+
text = text.strip()
|
| 123 |
+
if text.startswith('"') and text.endswith('"'):
|
| 124 |
+
text = text[1:-1]
|
| 125 |
+
|
| 126 |
+
tts_prompt = {text}
|
| 127 |
+
tts_emotion = "Warm, encouraging, and clear with a friendly and supportive tone."
|
| 128 |
+
|
| 129 |
+
return TTS_CLIENT.predict(
|
| 130 |
+
password=TTS_PASSWORD,
|
| 131 |
+
prompt=tts_prompt,
|
| 132 |
+
voice=TTS_VOICE,
|
| 133 |
+
emotion=tts_emotion,
|
| 134 |
+
use_random_seed=True,
|
| 135 |
+
specific_seed=TTS_SEED,
|
| 136 |
+
api_name="/text_to_speech_app"
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
# مثال على الاستخدام
|
| 140 |
+
if __name__ == "__main__":
|
| 141 |
+
tutor = EnglishTutor()
|
| 142 |
+
|
| 143 |
+
# الترحيب
|
| 144 |
+
welcome = tutor.get_welcome_message()
|
| 145 |
+
print("\n🤖 Sam:", welcome)
|
| 146 |
+
welcome_audio = tutor.text_to_speech(welcome)
|
| 147 |
+
print("Audio response saved to:", welcome_audio)
|
| 148 |
+
|
| 149 |
+
# المحادثة
|
| 150 |
+
while True:
|
| 151 |
+
user_input = input("\n👤 You: ")
|
| 152 |
+
if user_input.lower() in ['exit', 'quit', 'bye']:
|
| 153 |
+
print("\n🤖 Sam: Goodbye! Keep practicing your English! 👋")
|
| 154 |
+
break
|
| 155 |
+
|
| 156 |
+
response = tutor.get_bot_response(user_input)
|
| 157 |
+
main_response = response["response"].strip()
|
| 158 |
+
print("\n🤖 Sam:", main_response)
|
| 159 |
+
if response["corrections"]:
|
| 160 |
+
print("✍️ Corrections:", response["corrections"])
|
| 161 |
+
if response["vocabulary"]:
|
| 162 |
+
print("📚 Vocabulary:", response["vocabulary"])
|
| 163 |
+
if response["encouragement"]:
|
| 164 |
+
print("🌟 Encouragement:", response["encouragement"])
|
| 165 |
+
|
| 166 |
+
# تحويل الرد إلى صوت - نستخدم فقط الرد الرئيسي
|
| 167 |
+
audio_file = tutor.text_to_speech(main_response)
|
| 168 |
+
print("Audio response saved to:", audio_file)
|