Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -4,12 +4,13 @@ import json
|
|
| 4 |
import os
|
| 5 |
from datetime import datetime
|
| 6 |
|
| 7 |
-
# إعدادات
|
| 8 |
-
|
| 9 |
-
|
|
|
|
| 10 |
API_URL = f"https://router.huggingface.co/hf-inference/models/{MODEL_NAME}"
|
| 11 |
|
| 12 |
-
# إعداد headers
|
| 13 |
headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
|
| 14 |
|
| 15 |
class AstramindChatbot:
|
|
@@ -20,256 +21,189 @@ class AstramindChatbot:
|
|
| 20 |
|
| 21 |
def format_message(self, user_message):
|
| 22 |
"""تنسيق الرسالة للنموذج"""
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
| 28 |
|
| 29 |
-
|
| 30 |
-
for msg in self.conversation_history[-5:]:
|
| 31 |
-
role = "المستخدم" if msg["role"] == "user" else "أنت"
|
| 32 |
-
prompt += f"{role}: {msg['content']}\n"
|
| 33 |
-
|
| 34 |
-
prompt += "أنت:"
|
| 35 |
return prompt
|
| 36 |
|
| 37 |
-
def send_to_model(self, prompt):
|
| 38 |
-
"""إرسال للنموذج"""
|
| 39 |
try:
|
| 40 |
payload = {
|
| 41 |
"inputs": prompt,
|
| 42 |
"parameters": {
|
| 43 |
-
"max_new_tokens":
|
| 44 |
-
"temperature":
|
| 45 |
"top_p": 0.9,
|
| 46 |
"return_full_text": False,
|
| 47 |
"do_sample": True
|
| 48 |
}
|
| 49 |
}
|
| 50 |
|
| 51 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
|
| 53 |
if response.status_code == 200:
|
| 54 |
result = response.json()
|
| 55 |
|
| 56 |
-
# معالجة الرد
|
| 57 |
if isinstance(result, list) and len(result) > 0:
|
| 58 |
if 'generated_text' in result[0]:
|
| 59 |
full_response = result[0]['generated_text']
|
| 60 |
-
# استخراج رد ال
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
return bot_response
|
| 69 |
|
| 70 |
return "عذراً، لم أفهم الرد."
|
| 71 |
|
|
|
|
|
|
|
| 72 |
elif response.status_code == 503:
|
| 73 |
-
return "🔄 النموذج
|
| 74 |
else:
|
| 75 |
-
return f"⚠️ خطأ: {response.status_code}"
|
| 76 |
|
| 77 |
-
except requests.exceptions.Timeout:
|
| 78 |
-
return "⏳ النموذج يأخذ وقتاً، يرجى الانتظار..."
|
| 79 |
except Exception as e:
|
| 80 |
-
return f"❌ خطأ: {str(e)}"
|
| 81 |
|
| 82 |
-
def chat(self, user_message,
|
| 83 |
"""الدردشة مع البوت"""
|
| 84 |
if not user_message.strip():
|
| 85 |
-
return
|
| 86 |
|
| 87 |
-
# تنسيق الرسالة
|
| 88 |
prompt = self.format_message(user_message)
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
bot_response = self.send_to_model(prompt)
|
| 92 |
-
|
| 93 |
-
# تحديث التاريخ
|
| 94 |
-
history.append((user_message, bot_response))
|
| 95 |
-
|
| 96 |
-
return history, ""
|
| 97 |
|
| 98 |
# إنشاء البوت
|
| 99 |
chatbot = AstramindChatbot()
|
| 100 |
|
| 101 |
-
# واجهة Gradio
|
| 102 |
with gr.Blocks(
|
| 103 |
-
title="🤖 Astramind - مساعد الدردشة
|
| 104 |
-
theme=gr.themes.Soft()
|
| 105 |
-
css="""
|
| 106 |
-
.chatbot { height: 500px !important; }
|
| 107 |
-
.message.user { background-color: #e3f2fd; }
|
| 108 |
-
.message.bot { background-color: #f3e5f5; }
|
| 109 |
-
"""
|
| 110 |
) as demo:
|
| 111 |
|
| 112 |
-
# العنوان
|
| 113 |
gr.Markdown("""
|
| 114 |
# 🤖 Astramind - مساعد الدردشة الذكي
|
| 115 |
-
### تحدث مع النموذج العربي الخاص بك
|
| 116 |
""")
|
| 117 |
|
| 118 |
-
# معلومات
|
| 119 |
with gr.Row():
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
""")
|
| 127 |
-
|
| 128 |
-
with gr.Column(scale=2):
|
| 129 |
-
gr.Markdown("""
|
| 130 |
-
**تعليمات:**
|
| 131 |
-
1. اكتب رسالتك في المربع أدناه
|
| 132 |
-
2. اضغط Enter أو زر "إرسال"
|
| 133 |
-
3. انتظر رد البوت
|
| 134 |
-
""")
|
| 135 |
|
| 136 |
# منطقة المحادثة
|
| 137 |
-
|
| 138 |
-
label="المحادثة",
|
| 139 |
-
height=400,
|
| 140 |
-
avatar_images=(None, "https://cdn-icons-png.flaticon.com/512/4712/4712035.png")
|
| 141 |
-
)
|
| 142 |
|
| 143 |
# منطقة الإدخال
|
| 144 |
with gr.Row():
|
| 145 |
-
|
| 146 |
-
label="
|
| 147 |
-
placeholder="
|
| 148 |
-
|
| 149 |
-
|
| 150 |
)
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
submit_btn = gr.Button("إرسال", variant="primary", size="lg")
|
| 154 |
-
clear_btn = gr.Button("🗑️ مسح", variant="secondary")
|
| 155 |
|
| 156 |
-
#
|
| 157 |
-
with gr.Accordion("⚙️ الإعدادات
|
| 158 |
with gr.Row():
|
| 159 |
-
max_tokens = gr.Slider(
|
| 160 |
-
|
| 161 |
-
label="طول الرد"
|
| 162 |
-
)
|
| 163 |
-
temperature = gr.Slider(
|
| 164 |
-
minimum=0.1, maximum=1.0, value=0.7, step=0.1,
|
| 165 |
-
label="الإبداعية (Temperature)"
|
| 166 |
-
)
|
| 167 |
-
|
| 168 |
-
with gr.Row():
|
| 169 |
-
test_btn = gr.Button("🔍 اختبار الاتصال بالنموذج")
|
| 170 |
-
status_text = gr.Textbox(label="حالة الاتصال", interactive=False)
|
| 171 |
|
| 172 |
-
# أمثلة
|
| 173 |
gr.Markdown("### 💡 أمثلة سريعة:")
|
| 174 |
|
| 175 |
examples = gr.Examples(
|
| 176 |
examples=[
|
| 177 |
-
["السلام عليكم
|
| 178 |
-
["
|
| 179 |
-
["
|
| 180 |
-
["
|
| 181 |
-
["اكتب لي قصيدة صغيرة عن العلم"],
|
| 182 |
-
["كيف أتعلم البرمجة؟"]
|
| 183 |
],
|
| 184 |
-
inputs=
|
| 185 |
-
label="
|
| 186 |
)
|
| 187 |
|
| 188 |
-
#
|
| 189 |
-
|
| 190 |
-
|
|
|
|
|
|
|
| 191 |
if not message.strip():
|
| 192 |
-
return history, "", "
|
| 193 |
|
| 194 |
-
|
| 195 |
-
chatbot.send_to_model = lambda prompt: requests.post(
|
| 196 |
-
API_URL,
|
| 197 |
-
headers=headers,
|
| 198 |
-
json={
|
| 199 |
-
"inputs": prompt,
|
| 200 |
-
"parameters": {
|
| 201 |
-
"max_new_tokens": max_tokens_val,
|
| 202 |
-
"temperature": temp_val,
|
| 203 |
-
"top_p": 0.9,
|
| 204 |
-
"return_full_text": False
|
| 205 |
-
}
|
| 206 |
-
},
|
| 207 |
-
timeout=30
|
| 208 |
-
)
|
| 209 |
|
| 210 |
-
# الد
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
json={"inputs": "مرحبا"},
|
| 221 |
-
timeout=10
|
| 222 |
-
)
|
| 223 |
-
|
| 224 |
-
if test_response.status_code == 200:
|
| 225 |
-
return "✅ الاتصال ناجح! النموذج شغال."
|
| 226 |
-
elif test_response.status_code == 401:
|
| 227 |
-
return "⚠️ يحتاج Token. أضف HF_TOKEN في Secrets."
|
| 228 |
-
else:
|
| 229 |
-
return f"❌ خطأ: {test_response.status_code}"
|
| 230 |
-
|
| 231 |
-
except Exception as e:
|
| 232 |
-
return f"❌ خطأ اتصال: {str(e)}"
|
| 233 |
|
| 234 |
-
def
|
| 235 |
-
"""مسح المحادثة"""
|
| 236 |
chatbot.conversation_history = []
|
| 237 |
-
return [], "تم مسح المحادثة
|
| 238 |
|
| 239 |
# ربط الأحداث
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
[
|
| 243 |
-
[
|
| 244 |
)
|
| 245 |
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
[
|
| 249 |
-
[
|
| 250 |
)
|
| 251 |
|
| 252 |
clear_btn.click(
|
| 253 |
-
|
| 254 |
-
outputs=[
|
| 255 |
)
|
| 256 |
|
| 257 |
-
|
| 258 |
-
|
| 259 |
-
|
| 260 |
-
|
|
|
|
|
|
|
| 261 |
|
| 262 |
-
|
| 263 |
-
demo.load(
|
| 264 |
-
fn=lambda: "🚀 جاهز للدردشة! ابدأ بالكتابة...",
|
| 265 |
-
outputs=status_text
|
| 266 |
-
)
|
| 267 |
|
| 268 |
-
# تشغيل
|
| 269 |
if __name__ == "__main__":
|
| 270 |
demo.launch(
|
| 271 |
debug=True,
|
| 272 |
server_name="0.0.0.0",
|
| 273 |
-
server_port=7860
|
| 274 |
-
share=True # لينشئ رابط عام
|
| 275 |
)
|
|
|
|
| 4 |
import os
|
| 5 |
from datetime import datetime
|
| 6 |
|
| 7 |
+
# === إعدادات آمنة ===
|
| 8 |
+
# استخدم Environment Variables (Secrets) بدل وضع Token في الكود
|
| 9 |
+
MODEL_NAME = os.environ.get("MODEL_NAME", "kawkabelaloom/astramind")
|
| 10 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "") # سيأتي من Secrets
|
| 11 |
API_URL = f"https://router.huggingface.co/hf-inference/models/{MODEL_NAME}"
|
| 12 |
|
| 13 |
+
# إعداد headers بشكل آمن
|
| 14 |
headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
|
| 15 |
|
| 16 |
class AstramindChatbot:
|
|
|
|
| 21 |
|
| 22 |
def format_message(self, user_message):
|
| 23 |
"""تنسيق الرسالة للنموذج"""
|
| 24 |
+
if not self.conversation_history:
|
| 25 |
+
prompt = f"{self.system_prompt}\n\nالمستخدم: {user_message}\nأنت:"
|
| 26 |
+
else:
|
| 27 |
+
prompt = self.system_prompt + "\n\n"
|
| 28 |
+
for msg in self.conversation_history[-3:]:
|
| 29 |
+
role = "المستخدم" if msg["role"] == "user" else "أنت"
|
| 30 |
+
prompt += f"{role}: {msg['content']}\n"
|
| 31 |
+
prompt += f"المستخدم: {user_message}\nأنت:"
|
| 32 |
|
| 33 |
+
self.conversation_history.append({"role": "user", "content": user_message})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
return prompt
|
| 35 |
|
| 36 |
+
def send_to_model(self, prompt, max_tokens=200, temperature=0.7):
|
| 37 |
+
"""إرسال للنموذج - بدون token إذا مش متاح"""
|
| 38 |
try:
|
| 39 |
payload = {
|
| 40 |
"inputs": prompt,
|
| 41 |
"parameters": {
|
| 42 |
+
"max_new_tokens": max_tokens,
|
| 43 |
+
"temperature": temperature,
|
| 44 |
"top_p": 0.9,
|
| 45 |
"return_full_text": False,
|
| 46 |
"do_sample": True
|
| 47 |
}
|
| 48 |
}
|
| 49 |
|
| 50 |
+
# إذا بدون token، جرب نموذج عام بديل
|
| 51 |
+
if not HF_TOKEN:
|
| 52 |
+
# استخدم نموذج Qwen العام بدون token
|
| 53 |
+
alt_url = "https://router.huggingface.co/hf-inference/models/Qwen/Qwen2.5-7B-Instruct"
|
| 54 |
+
response = requests.post(alt_url, json=payload, timeout=20)
|
| 55 |
+
else:
|
| 56 |
+
response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
|
| 57 |
|
| 58 |
if response.status_code == 200:
|
| 59 |
result = response.json()
|
| 60 |
|
|
|
|
| 61 |
if isinstance(result, list) and len(result) > 0:
|
| 62 |
if 'generated_text' in result[0]:
|
| 63 |
full_response = result[0]['generated_text']
|
| 64 |
+
# استخراج الرد الأخير
|
| 65 |
+
lines = full_response.split('\n')
|
| 66 |
+
for line in reversed(lines):
|
| 67 |
+
if line.strip() and not line.startswith('المستخدم:'):
|
| 68 |
+
bot_response = line.replace('أنت:', '').strip()
|
| 69 |
+
if bot_response:
|
| 70 |
+
self.conversation_history.append({"role": "assistant", "content": bot_response})
|
| 71 |
+
return bot_response
|
|
|
|
| 72 |
|
| 73 |
return "عذراً، لم أفهم الرد."
|
| 74 |
|
| 75 |
+
elif response.status_code in [401, 403]:
|
| 76 |
+
return "⚠️ يبدو أن هناك مشكلة في التوكن. جاري استخدام نموذج بديل..."
|
| 77 |
elif response.status_code == 503:
|
| 78 |
+
return "🔄 النموذج مشغول الآن، جرب مرة أخرى بعد قليل."
|
| 79 |
else:
|
| 80 |
+
return f"⚠️ حدث خطأ: {response.status_code}"
|
| 81 |
|
|
|
|
|
|
|
| 82 |
except Exception as e:
|
| 83 |
+
return f"❌ خطأ في الاتصال: {str(e)[:100]}"
|
| 84 |
|
| 85 |
+
def chat(self, user_message, max_tokens=200, temperature=0.7):
|
| 86 |
"""الدردشة مع البوت"""
|
| 87 |
if not user_message.strip():
|
| 88 |
+
return "⚠️ الرجاء كتابة رسالة."
|
| 89 |
|
|
|
|
| 90 |
prompt = self.format_message(user_message)
|
| 91 |
+
bot_response = self.send_to_model(prompt, max_tokens, temperature)
|
| 92 |
+
return bot_response
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
|
| 94 |
# إنشاء البوت
|
| 95 |
chatbot = AstramindChatbot()
|
| 96 |
|
| 97 |
+
# === واجهة Gradio ===
|
| 98 |
with gr.Blocks(
|
| 99 |
+
title="🤖 Astramind - مساعد الدردشة",
|
| 100 |
+
theme=gr.themes.Soft()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
) as demo:
|
| 102 |
|
|
|
|
| 103 |
gr.Markdown("""
|
| 104 |
# 🤖 Astramind - مساعد الدردشة الذكي
|
| 105 |
+
### تحدث مع النموذج العربي الخاص بك
|
| 106 |
""")
|
| 107 |
|
| 108 |
+
# معلومات
|
| 109 |
with gr.Row():
|
| 110 |
+
gr.Markdown(f"""
|
| 111 |
+
**المعلومات:**
|
| 112 |
+
- النموذج: `{MODEL_NAME if HF_TOKEN else 'Qwen/Qwen2.5-7B-Instruct (بديل)'}`
|
| 113 |
+
- الحالة: {'🔐 باستخدام Token' if HF_TOKEN else '🔓 بدون Token (بديل)'}
|
| 114 |
+
- الوقت: {datetime.now().strftime('%H:%M')}
|
| 115 |
+
""")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
|
| 117 |
# منطقة المحادثة
|
| 118 |
+
chatbot_display = gr.Chatbot(label="المحادثة", height=400)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 119 |
|
| 120 |
# منطقة الإدخال
|
| 121 |
with gr.Row():
|
| 122 |
+
user_input = gr.Textbox(
|
| 123 |
+
label="رسالتك",
|
| 124 |
+
placeholder="اكتب سؤالك هنا...",
|
| 125 |
+
lines=2,
|
| 126 |
+
scale=4
|
| 127 |
)
|
| 128 |
+
send_btn = gr.Button("إرسال", variant="primary")
|
| 129 |
+
clear_btn = gr.Button("مسح", variant="secondary")
|
|
|
|
|
|
|
| 130 |
|
| 131 |
+
# إعدادات
|
| 132 |
+
with gr.Accordion("⚙️ الإعدادات", open=False):
|
| 133 |
with gr.Row():
|
| 134 |
+
max_tokens = gr.Slider(50, 500, value=200, label="طول الرد")
|
| 135 |
+
temperature = gr.Slider(0.1, 1.0, value=0.7, label="الإبداعية")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
+
# أمثلة
|
| 138 |
gr.Markdown("### 💡 أمثلة سريعة:")
|
| 139 |
|
| 140 |
examples = gr.Examples(
|
| 141 |
examples=[
|
| 142 |
+
["السلام عليكم"],
|
| 143 |
+
["ما هو اسمك؟"],
|
| 144 |
+
["كيف يمكنني التسجيل؟"],
|
| 145 |
+
["أخبرني نكتة"]
|
|
|
|
|
|
|
| 146 |
],
|
| 147 |
+
inputs=user_input,
|
| 148 |
+
label="جرب أحد هذه الأمثلة"
|
| 149 |
)
|
| 150 |
|
| 151 |
+
# متغير حالة
|
| 152 |
+
status = gr.Textbox(label="الحالة", interactive=False)
|
| 153 |
+
|
| 154 |
+
# وظائف
|
| 155 |
+
def respond(message, history, tokens, temp):
|
| 156 |
if not message.strip():
|
| 157 |
+
return history, "", "اكتب رسالة أولاً"
|
| 158 |
|
| 159 |
+
response = chatbot.chat(message, tokens, temp)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 160 |
|
| 161 |
+
# تحديث المحادثة
|
| 162 |
+
if history is None:
|
| 163 |
+
history = []
|
| 164 |
+
history.append((message, response))
|
| 165 |
+
|
| 166 |
+
# تحديث الحالة
|
| 167 |
+
model_used = MODEL_NAME if HF_TOKEN else "Qwen (بديل)"
|
| 168 |
+
status_msg = f"✅ تم الرد باستخدام: {model_used}"
|
| 169 |
+
|
| 170 |
+
return history, "", status_msg
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
+
def clear_history():
|
|
|
|
| 173 |
chatbot.conversation_history = []
|
| 174 |
+
return [], "تم مسح المحادثة"
|
| 175 |
|
| 176 |
# ربط الأحداث
|
| 177 |
+
user_input.submit(
|
| 178 |
+
respond,
|
| 179 |
+
[user_input, chatbot_display, max_tokens, temperature],
|
| 180 |
+
[chatbot_display, user_input, status]
|
| 181 |
)
|
| 182 |
|
| 183 |
+
send_btn.click(
|
| 184 |
+
respond,
|
| 185 |
+
[user_input, chatbot_display, max_tokens, temperature],
|
| 186 |
+
[chatbot_display, user_input, status]
|
| 187 |
)
|
| 188 |
|
| 189 |
clear_btn.click(
|
| 190 |
+
clear_history,
|
| 191 |
+
outputs=[chatbot_display, status]
|
| 192 |
)
|
| 193 |
|
| 194 |
+
# رسالة ترحيب
|
| 195 |
+
def welcome_message():
|
| 196 |
+
if HF_TOKEN:
|
| 197 |
+
return f"🚀 جاهز! النموذج: {MODEL_NAME}"
|
| 198 |
+
else:
|
| 199 |
+
return "🚀 جاهز! باستخدام نموذج Qwen البديل (بدون Token)"
|
| 200 |
|
| 201 |
+
demo.load(welcome_message, outputs=status)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
+
# التشغيل
|
| 204 |
if __name__ == "__main__":
|
| 205 |
demo.launch(
|
| 206 |
debug=True,
|
| 207 |
server_name="0.0.0.0",
|
| 208 |
+
server_port=7860
|
|
|
|
| 209 |
)
|