Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,114 +1,130 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
| 3 |
import os
|
|
|
|
| 4 |
from datetime import datetime
|
| 5 |
|
| 6 |
-
# ===
|
|
|
|
|
|
|
| 7 |
MODEL_NAME = os.environ.get("MODEL_NAME", "kawkabelaloom/astramind")
|
| 8 |
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 9 |
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"
|
| 10 |
|
| 11 |
-
headers = {
|
|
|
|
|
|
|
|
|
|
| 12 |
|
|
|
|
|
|
|
|
|
|
| 13 |
class AstramindChatbot:
|
| 14 |
def __init__(self):
|
| 15 |
self.conversation_history = []
|
| 16 |
-
self.system_prompt =
|
| 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 |
-
# آخر 3 رسائل
|
| 43 |
-
for msg in self.conversation_history[-6:]:
|
| 44 |
-
messages.append({
|
| 45 |
-
"role": msg["role"],
|
| 46 |
-
"content": msg["content"]
|
| 47 |
-
})
|
| 48 |
-
|
| 49 |
-
messages.append({"role": "user", "content": user_message})
|
| 50 |
-
|
| 51 |
-
payload = {
|
| 52 |
-
"messages": messages,
|
| 53 |
-
"parameters": {
|
| 54 |
-
"max_new_tokens": max_tokens,
|
| 55 |
-
"temperature": temperature,
|
| 56 |
-
"top_p": 0.9
|
| 57 |
}
|
| 58 |
-
}
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
json
|
| 64 |
-
|
| 65 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
-
|
| 68 |
-
|
| 69 |
|
| 70 |
-
#
|
| 71 |
-
if
|
| 72 |
-
|
| 73 |
-
else:
|
| 74 |
-
bot_response = str(result)
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
|
| 80 |
-
|
|
|
|
|
|
|
| 81 |
|
| 82 |
-
|
| 83 |
-
|
|
|
|
| 84 |
|
| 85 |
-
|
| 86 |
-
return f"⚠️ Error {response.status_code}: {response.text[:200]}"
|
| 87 |
|
| 88 |
-
|
| 89 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 90 |
|
| 91 |
def chat(self, user_message, max_tokens=200, temperature=0.7):
|
| 92 |
if not user_message.strip():
|
| 93 |
return "⚠️ الرجاء كتابة رسالة."
|
| 94 |
-
|
| 95 |
return self.send_to_model(user_message, max_tokens, temperature)
|
| 96 |
|
| 97 |
-
#
|
|
|
|
|
|
|
| 98 |
chatbot = AstramindChatbot()
|
| 99 |
|
| 100 |
-
# ===
|
|
|
|
|
|
|
| 101 |
def respond(message, history, tokens, temp):
|
| 102 |
-
if not message.strip():
|
| 103 |
-
return history, "", "اكتب رسالة أولاً"
|
| 104 |
-
|
| 105 |
-
response = chatbot.chat(message, tokens, temp)
|
| 106 |
-
|
| 107 |
history = history or []
|
|
|
|
|
|
|
| 108 |
history.append((message, response))
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
def clear_chat():
|
| 114 |
chatbot.conversation_history = []
|
|
@@ -116,99 +132,81 @@ def clear_chat():
|
|
| 116 |
|
| 117 |
def welcome_message():
|
| 118 |
if HF_TOKEN:
|
| 119 |
-
return f"🤖 Astramind
|
| 120 |
-
|
| 121 |
-
return "⚠️ يرجى إضافة HF_TOKEN في Secrets"
|
| 122 |
|
| 123 |
-
#
|
|
|
|
|
|
|
| 124 |
with gr.Blocks(title="Astramind Chatbot") as demo:
|
| 125 |
-
|
| 126 |
-
gr.Markdown("#
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
# حالة النظام
|
| 130 |
status_box = gr.Textbox(
|
| 131 |
value=welcome_message(),
|
| 132 |
label="الحالة",
|
| 133 |
interactive=False
|
| 134 |
)
|
| 135 |
-
|
| 136 |
-
# شات بوت
|
| 137 |
chatbot_ui = gr.Chatbot(
|
| 138 |
label="المحادثة",
|
| 139 |
-
height=400
|
| 140 |
-
show_label=True
|
| 141 |
)
|
| 142 |
-
|
| 143 |
-
# إدخال الرسالة
|
| 144 |
with gr.Row():
|
| 145 |
message_input = gr.Textbox(
|
| 146 |
placeholder="اكتب رسالتك هنا...",
|
| 147 |
-
label="رسالتك",
|
| 148 |
lines=2,
|
| 149 |
scale=4
|
| 150 |
)
|
| 151 |
send_btn = gr.Button("إرسال", variant="primary")
|
| 152 |
-
|
| 153 |
-
# أزرار التحكم
|
| 154 |
with gr.Row():
|
| 155 |
-
clear_btn = gr.Button("مسح المحادثة"
|
| 156 |
-
gr.Button("🔄"
|
| 157 |
-
|
| 158 |
-
outputs=status_box
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
-
# إعدادات
|
| 162 |
with gr.Accordion("⚙️ الإعدادات", open=False):
|
| 163 |
-
max_tokens = gr.Slider(
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
step=10
|
| 167 |
-
)
|
| 168 |
-
temperature = gr.Slider(
|
| 169 |
-
0.1, 1.0, value=0.7,
|
| 170 |
-
label="الإبداعية",
|
| 171 |
-
step=0.1
|
| 172 |
-
)
|
| 173 |
-
|
| 174 |
-
# أمثلة
|
| 175 |
gr.Examples(
|
| 176 |
examples=[
|
| 177 |
["السلام عليكم"],
|
| 178 |
-
["م
|
| 179 |
-
["
|
| 180 |
-
["كيف
|
| 181 |
],
|
| 182 |
-
inputs=message_input
|
| 183 |
-
label="💡 أمثلة سريعة"
|
| 184 |
)
|
| 185 |
-
|
| 186 |
-
# أحداث
|
| 187 |
-
def submit_message(message, history, tokens, temp):
|
| 188 |
-
return respond(message, history, tokens, temp)
|
| 189 |
-
|
| 190 |
-
# ربط الأحداث
|
| 191 |
send_btn.click(
|
| 192 |
-
|
| 193 |
inputs=[message_input, chatbot_ui, max_tokens, temperature],
|
| 194 |
outputs=[chatbot_ui, message_input, status_box]
|
| 195 |
)
|
| 196 |
-
|
| 197 |
message_input.submit(
|
| 198 |
-
|
| 199 |
inputs=[message_input, chatbot_ui, max_tokens, temperature],
|
| 200 |
outputs=[chatbot_ui, message_input, status_box]
|
| 201 |
)
|
| 202 |
-
|
| 203 |
clear_btn.click(
|
| 204 |
-
|
| 205 |
outputs=[chatbot_ui, status_box]
|
| 206 |
)
|
| 207 |
|
| 208 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 209 |
if __name__ == "__main__":
|
| 210 |
demo.launch(
|
| 211 |
server_name="0.0.0.0",
|
| 212 |
server_port=7860,
|
| 213 |
debug=True
|
| 214 |
-
)
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
import requests
|
| 3 |
import os
|
| 4 |
+
import json
|
| 5 |
from datetime import datetime
|
| 6 |
|
| 7 |
+
# ===============================
|
| 8 |
+
# 🔧 الإعدادات
|
| 9 |
+
# ===============================
|
| 10 |
MODEL_NAME = os.environ.get("MODEL_NAME", "kawkabelaloom/astramind")
|
| 11 |
HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 12 |
API_URL = f"https://api-inference.huggingface.co/models/{MODEL_NAME}"
|
| 13 |
|
| 14 |
+
headers = {
|
| 15 |
+
"Authorization": f"Bearer {HF_TOKEN}",
|
| 16 |
+
"Content-Type": "application/json"
|
| 17 |
+
} if HF_TOKEN else {}
|
| 18 |
|
| 19 |
+
# ===============================
|
| 20 |
+
# 🤖 Chatbot Class
|
| 21 |
+
# ===============================
|
| 22 |
class AstramindChatbot:
|
| 23 |
def __init__(self):
|
| 24 |
self.conversation_history = []
|
| 25 |
+
self.system_prompt = (
|
| 26 |
+
"أنت مساعد عربي ذكي اسمك أسترا. "
|
| 27 |
+
"تحدث بلغة عربية واضحة، مختصرة ومفيدة."
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
def send_to_model(self, user_message, max_tokens=200, temperature=0.7):
|
| 31 |
+
try:
|
| 32 |
+
# ===== تجهيز الرسائل =====
|
| 33 |
+
messages = [{"role": "system", "content": self.system_prompt}]
|
| 34 |
+
|
| 35 |
+
for msg in self.conversation_history[-6:]:
|
| 36 |
+
messages.append({
|
| 37 |
+
"role": msg["role"],
|
| 38 |
+
"content": msg["content"]
|
| 39 |
+
})
|
| 40 |
+
|
| 41 |
+
messages.append({"role": "user", "content": user_message})
|
| 42 |
+
|
| 43 |
+
payload = {
|
| 44 |
+
"messages": messages,
|
| 45 |
+
"parameters": {
|
| 46 |
+
"max_new_tokens": max_tokens,
|
| 47 |
+
"temperature": temperature,
|
| 48 |
+
"top_p": 0.9
|
| 49 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
}
|
|
|
|
| 51 |
|
| 52 |
+
# ===== Debug Logs =====
|
| 53 |
+
print("\n==============================")
|
| 54 |
+
print("📤 REQUEST PAYLOAD:")
|
| 55 |
+
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
| 56 |
+
print("==============================")
|
| 57 |
+
|
| 58 |
+
response = requests.post(
|
| 59 |
+
API_URL,
|
| 60 |
+
headers=headers,
|
| 61 |
+
json=payload,
|
| 62 |
+
timeout=60
|
| 63 |
+
)
|
| 64 |
|
| 65 |
+
print(f"📥 STATUS CODE: {response.status_code}")
|
| 66 |
+
print(f"📥 RAW RESPONSE: {response.text[:500]}")
|
| 67 |
|
| 68 |
+
# ===== Success =====
|
| 69 |
+
if response.status_code == 200:
|
| 70 |
+
result = response.json()
|
|
|
|
|
|
|
| 71 |
|
| 72 |
+
# HuggingFace Chat format
|
| 73 |
+
if isinstance(result, dict) and "choices" in result:
|
| 74 |
+
bot_response = result["choices"][0]["message"]["content"]
|
| 75 |
|
| 76 |
+
# Fallback
|
| 77 |
+
else:
|
| 78 |
+
bot_response = str(result)
|
| 79 |
|
| 80 |
+
self.conversation_history.append(
|
| 81 |
+
{"role": "assistant", "content": bot_response}
|
| 82 |
+
)
|
| 83 |
|
| 84 |
+
return bot_response.strip()
|
|
|
|
| 85 |
|
| 86 |
+
# ===== Model Loading =====
|
| 87 |
+
elif response.status_code == 503:
|
| 88 |
+
return "🔄 النموذج جاري التحميل… حاول مرة أخرى بعد دقيقة."
|
| 89 |
+
|
| 90 |
+
# ===== Any Other Error =====
|
| 91 |
+
else:
|
| 92 |
+
return (
|
| 93 |
+
f"❌ API ERROR\n"
|
| 94 |
+
f"Status: {response.status_code}\n"
|
| 95 |
+
f"Response: {response.text}"
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
except Exception as e:
|
| 99 |
+
return (
|
| 100 |
+
"❌ PYTHON EXCEPTION\n"
|
| 101 |
+
f"{str(e)}"
|
| 102 |
+
)
|
| 103 |
|
| 104 |
def chat(self, user_message, max_tokens=200, temperature=0.7):
|
| 105 |
if not user_message.strip():
|
| 106 |
return "⚠️ الرجاء كتابة رسالة."
|
|
|
|
| 107 |
return self.send_to_model(user_message, max_tokens, temperature)
|
| 108 |
|
| 109 |
+
# ===============================
|
| 110 |
+
# 🚀 إنشاء البوت
|
| 111 |
+
# ===============================
|
| 112 |
chatbot = AstramindChatbot()
|
| 113 |
|
| 114 |
+
# ===============================
|
| 115 |
+
# 🎛️ Gradio Functions
|
| 116 |
+
# ===============================
|
| 117 |
def respond(message, history, tokens, temp):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 118 |
history = history or []
|
| 119 |
+
|
| 120 |
+
response = chatbot.chat(message, tokens, temp)
|
| 121 |
history.append((message, response))
|
| 122 |
+
|
| 123 |
+
status = "✅ تم التنفيذ"
|
| 124 |
+
if response.startswith("❌"):
|
| 125 |
+
status = "🚨 يوجد خطأ — راجع الرسالة"
|
| 126 |
+
|
| 127 |
+
return history, "", status
|
| 128 |
|
| 129 |
def clear_chat():
|
| 130 |
chatbot.conversation_history = []
|
|
|
|
| 132 |
|
| 133 |
def welcome_message():
|
| 134 |
if HF_TOKEN:
|
| 135 |
+
return f"🤖 Astramind Ready | Model: {MODEL_NAME}"
|
| 136 |
+
return "⚠️ HF_TOKEN غير موجود في Secrets"
|
|
|
|
| 137 |
|
| 138 |
+
# ===============================
|
| 139 |
+
# 🖥️ Gradio UI
|
| 140 |
+
# ===============================
|
| 141 |
with gr.Blocks(title="Astramind Chatbot") as demo:
|
| 142 |
+
gr.Markdown("# 🤖 Astramind")
|
| 143 |
+
gr.Markdown("### مساعد دردشة عربي مبني على HuggingFace")
|
| 144 |
+
|
|
|
|
|
|
|
| 145 |
status_box = gr.Textbox(
|
| 146 |
value=welcome_message(),
|
| 147 |
label="الحالة",
|
| 148 |
interactive=False
|
| 149 |
)
|
| 150 |
+
|
|
|
|
| 151 |
chatbot_ui = gr.Chatbot(
|
| 152 |
label="المحادثة",
|
| 153 |
+
height=400
|
|
|
|
| 154 |
)
|
| 155 |
+
|
|
|
|
| 156 |
with gr.Row():
|
| 157 |
message_input = gr.Textbox(
|
| 158 |
placeholder="اكتب رسالتك هنا...",
|
|
|
|
| 159 |
lines=2,
|
| 160 |
scale=4
|
| 161 |
)
|
| 162 |
send_btn = gr.Button("إرسال", variant="primary")
|
| 163 |
+
|
|
|
|
| 164 |
with gr.Row():
|
| 165 |
+
clear_btn = gr.Button("مسح المحادثة")
|
| 166 |
+
refresh_btn = gr.Button("🔄")
|
| 167 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
with gr.Accordion("⚙️ الإعدادات", open=False):
|
| 169 |
+
max_tokens = gr.Slider(50, 500, value=200, step=10, label="طول الرد")
|
| 170 |
+
temperature = gr.Slider(0.1, 1.0, value=0.7, step=0.1, label="الإبداعية")
|
| 171 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
gr.Examples(
|
| 173 |
examples=[
|
| 174 |
["السلام عليكم"],
|
| 175 |
+
["من أنت؟"],
|
| 176 |
+
["احكي لي عن نفسك"],
|
| 177 |
+
["كيف أتعلم الذكاء الاصطناعي؟"]
|
| 178 |
],
|
| 179 |
+
inputs=message_input
|
|
|
|
| 180 |
)
|
| 181 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
send_btn.click(
|
| 183 |
+
respond,
|
| 184 |
inputs=[message_input, chatbot_ui, max_tokens, temperature],
|
| 185 |
outputs=[chatbot_ui, message_input, status_box]
|
| 186 |
)
|
| 187 |
+
|
| 188 |
message_input.submit(
|
| 189 |
+
respond,
|
| 190 |
inputs=[message_input, chatbot_ui, max_tokens, temperature],
|
| 191 |
outputs=[chatbot_ui, message_input, status_box]
|
| 192 |
)
|
| 193 |
+
|
| 194 |
clear_btn.click(
|
| 195 |
+
clear_chat,
|
| 196 |
outputs=[chatbot_ui, status_box]
|
| 197 |
)
|
| 198 |
|
| 199 |
+
refresh_btn.click(
|
| 200 |
+
fn=welcome_message,
|
| 201 |
+
outputs=status_box
|
| 202 |
+
)
|
| 203 |
+
|
| 204 |
+
# ===============================
|
| 205 |
+
# ▶️ Run
|
| 206 |
+
# ===============================
|
| 207 |
if __name__ == "__main__":
|
| 208 |
demo.launch(
|
| 209 |
server_name="0.0.0.0",
|
| 210 |
server_port=7860,
|
| 211 |
debug=True
|
| 212 |
+
)
|