Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,59 +1,275 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
| 3 |
import json
|
|
|
|
|
|
|
| 4 |
|
| 5 |
-
#
|
| 6 |
-
|
|
|
|
|
|
|
| 7 |
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
"
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
|
| 21 |
-
|
|
|
|
| 22 |
try:
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ات
|
| 8 |
+
MODEL_NAME = "kawkabelaloom/astramind" # نموذجك
|
| 9 |
+
HF_TOKEN = os.environ.get("HF_TOKEN", "") # ضعه في Space Secrets
|
| 10 |
+
API_URL = f"https://router.huggingface.co/hf-inference/models/{MODEL_NAME}"
|
| 11 |
|
| 12 |
+
# إعداد headers إذا كان هناك token
|
| 13 |
+
headers = {"Authorization": f"Bearer {HF_TOKEN}"} if HF_TOKEN else {}
|
| 14 |
+
|
| 15 |
+
class AstramindChatbot:
|
| 16 |
+
def __init__(self):
|
| 17 |
+
self.conversation_history = []
|
| 18 |
+
self.system_prompt = """أنت مساعد عربي ذكي اسمك "أسترا".
|
| 19 |
+
أجب بلغة عربية واضحة ومفيدة. كن ودوداً ومتعاوناً."""
|
| 20 |
|
| 21 |
+
def format_message(self, user_message):
|
| 22 |
+
"""تنسيق الرسالة للنموذج"""
|
| 23 |
+
# إضافة الرسالة للتاريخ
|
| 24 |
+
self.conversation_history.append({"role": "user", "content": user_message})
|
| 25 |
+
|
| 26 |
+
# بناء prompt مع التاريخ
|
| 27 |
+
prompt = self.system_prompt + "\n\n"
|
| 28 |
+
|
| 29 |
+
# إضافة آخر 5 رسائل من التاريخ
|
| 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": 300,
|
| 44 |
+
"temperature": 0.7,
|
| 45 |
+
"top_p": 0.9,
|
| 46 |
+
"return_full_text": False,
|
| 47 |
+
"do_sample": True
|
| 48 |
+
}
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
response = requests.post(API_URL, headers=headers, json=payload, timeout=30)
|
| 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 |
+
if prompt in full_response:
|
| 62 |
+
bot_response = full_response.replace(prompt, "").strip()
|
| 63 |
+
else:
|
| 64 |
+
bot_response = full_response
|
| 65 |
+
|
| 66 |
+
# إضافة للتاريخ
|
| 67 |
+
self.conversation_history.append({"role": "assistant", "content": bot_response})
|
| 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, history):
|
| 83 |
+
"""الدردشة مع البوت"""
|
| 84 |
+
if not user_message.strip():
|
| 85 |
+
return history, "⚠️ الرجاء كتابة رسالة."
|
| 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 |
+
with gr.Column(scale=1):
|
| 121 |
+
gr.Markdown(f"""
|
| 122 |
+
**معلومات النموذج:**
|
| 123 |
+
- الاسم: `{MODEL_NAME}`
|
| 124 |
+
- الحالة: {'🔒 يحتاج Token' if HF_TOKEN else '🔓 Public'}
|
| 125 |
+
- آخر تحديث: {datetime.now().strftime('%Y-%m-%d %H:%M')}
|
| 126 |
+
""")
|
| 127 |
+
|
| 128 |
+
with gr.Column(scale=2):
|
| 129 |
+
gr.Markdown("""
|
| 130 |
+
**تعليمات:**
|
| 131 |
+
1. اكتب رسالتك في المربع أدناه
|
| 132 |
+
2. اضغط Enter أو زر "إرسال"
|
| 133 |
+
3. انتظر رد البوت
|
| 134 |
+
""")
|
| 135 |
+
|
| 136 |
+
# منطقة المحادثة
|
| 137 |
+
chatbot_ui = gr.Chatbot(
|
| 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 |
+
msg = gr.Textbox(
|
| 146 |
+
label="اكتب رسالتك هنا",
|
| 147 |
+
placeholder="مثال: السلام عليكم، كيف حالك؟",
|
| 148 |
+
scale=4,
|
| 149 |
+
lines=2
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
with gr.Column(scale=1):
|
| 153 |
+
submit_btn = gr.Button("إرسال", variant="primary", size="lg")
|
| 154 |
+
clear_btn = gr.Button("🗑️ مسح", variant="secondary")
|
| 155 |
+
|
| 156 |
+
# منطقة التحكم
|
| 157 |
+
with gr.Accordion("⚙️ الإعدادات المتقدمة", open=False):
|
| 158 |
+
with gr.Row():
|
| 159 |
+
max_tokens = gr.Slider(
|
| 160 |
+
minimum=50, maximum=500, value=200, step=50,
|
| 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=msg,
|
| 185 |
+
label="اضغط على أي مثال لتجربته"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
# وظائف التحكم
|
| 189 |
+
def process_message(message, history, max_tokens_val, temp_val):
|
| 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 |
+
new_history, _ = chatbot.chat(message, history)
|
| 212 |
+
return new_history, "", f"✅ تم الرد (الطول: {max_tokens_val}, الإبداعية: {temp_val})"
|
| 213 |
+
|
| 214 |
+
def test_connection():
|
| 215 |
+
"""اختبار اتصال بالنموذج"""
|
| 216 |
+
try:
|
| 217 |
+
test_response = requests.post(
|
| 218 |
+
API_URL,
|
| 219 |
+
headers=headers,
|
| 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 clear_chat():
|
| 235 |
+
"""مسح المحادثة"""
|
| 236 |
+
chatbot.conversation_history = []
|
| 237 |
+
return [], "تم مسح المحادثة."
|
| 238 |
+
|
| 239 |
+
# ربط الأحداث
|
| 240 |
+
msg.submit(
|
| 241 |
+
process_message,
|
| 242 |
+
[msg, chatbot_ui, max_tokens, temperature],
|
| 243 |
+
[chatbot_ui, msg, status_text]
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
submit_btn.click(
|
| 247 |
+
process_message,
|
| 248 |
+
[msg, chatbot_ui, max_tokens, temperature],
|
| 249 |
+
[chatbot_ui, msg, status_text]
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
clear_btn.click(
|
| 253 |
+
clear_chat,
|
| 254 |
+
outputs=[chatbot_ui, status_text]
|
| 255 |
+
)
|
| 256 |
|
| 257 |
+
test_btn.click(
|
| 258 |
+
test_connection,
|
| 259 |
+
outputs=status_text
|
| 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 |
+
)
|