Spaces:
Runtime error
Runtime error
Update app.py
Browse files3 unmodified lines4567789105 unmodified lines16171819192021222323242526262728293031323334353629303132333435363738394041423839404441424344454746474849515051525354555556575859605657615859602 unmodified lines6364657071666768737475697071798081827273838474867576888990777879928081949596829883841001011028510410510610710886878811111211311489901161171181199192939495961229798124991001011271021031291041051061071081091321331341351361371101111121131391141151161411421431171181451461471481191201501511521531541551211221231241571581591601611251261271281631641651661291301311681691701711721731741321331761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232241343 unmodified linesimport json
# ===============================# 🔧 الإعدادات# 🔧 Settings# ===============================MODEL_NAME = os.environ.get("MODEL_NAME", "kawkabelaloom/astramind")HF_TOKEN = os.environ.get("HF_TOKEN", "")5 unmodified lines} if HF_TOKEN else {}
# ===============================# 🤖 Chatbot Class# 🤖 Chatbot# ===============================class AstramindChatbot: def __init__(self): self.conversation_history = [] self.history = [] self.system_prompt = ( "أنت مساعد عربي ذكي اسمك أسترا. " "أجب بلغة عربية واضحة ومفيدة." "أجب بلغة عربية واضحة ومفيدة.\n\n" )
def send_to_model(self, user_message, max_tokens=200, temperature=0.7): try: # =============================== # ✅ FORMAT CORRECT FOR HF # =============================== inputs = [ {"role": "system", "content": self.system_prompt} ] def build_prompt(self, user_message): prompt = self.system_prompt
for msg in self.history[-6:]: if msg["role"] == "user": prompt += f"المستخدم: {msg['content']}\n" else: prompt += f"المساعد: {msg['content']}\n"
for msg in self.conversation_history[-6:]: inputs.append({ "role": msg["role"], "content": msg["content"] }) prompt += f"المستخدم: {user_message}\nالمساعد:" return prompt
inputs.append({"role": "user", "content": user_message}) def send_to_model(self, user_message, max_tokens, temperature): try: prompt = self.build_prompt(user_message)
payload = { "inputs": inputs, "inputs": prompt, "parameters": { "max_new_tokens": max_tokens, "temperature": temperature, "top_p": 0.9 "top_p": 0.9, "do_sample": True, "return_full_text": False } }
# =============================== # 🐞 DEBUG LOGS # =============================== print("\n==============================") print("📤 PAYLOAD:") print(json.dumps(payload, ensure_ascii=False, indent=2)) print("\n📤 PROMPT SENT:\n", prompt) print("\n📤 PAYLOAD:\n", json.dumps(payload, ensure_ascii=False, indent=2)) print("==============================")
response = requests.post( API_URL,2 unmodified lines timeout=60 )
print(f"📥 STATUS: {response.status_code}") print(f"📥 RESPONSE RAW: {response.text[:500]}") print("📥 STATUS:", response.status_code) print("📥 RAW:", response.text[:500])
# =============================== # ✅ SUCCESS # =============================== if response.status_code == 200: result = response.json()
# HF غالباً بيرجع List if isinstance(result, list) and len(result) > 0: if "generated_text" in result[0]: bot_response = result[0]["generated_text"] if isinstance(result, list) and "generated_text" in result[0]: answer = result[0]["generated_text"] else: bot_response = str(result[0]) else: bot_response = str(result) answer = str(result)
self.conversation_history.append( {"role": "assistant", "content": bot_response} ) self.history.append({"role": "user", "content": user_message}) self.history.append({"role": "assistant", "content": answer})
return bot_response.strip() return answer.strip()
# =============================== # ⏳ MODEL LOADING # =============================== elif response.status_code == 503: return "🔄 النموذج جاري التحميل… حاول بعد دقيقة." return "🔄 النموذج بيحمّل… حاول بعد دقيقة"
# =============================== # ❌ API ERROR # =============================== else: return ( f"❌ API ERROR\n" f"Status: {response.status_code}\n" f"Response: {response.text}" ) return f"❌ API ERROR {response.status_code}\n{response.text}"
except Exception as e: return ( "❌ PYTHON EXCEPTION\n" f"{str(e)}" ) return f"❌ PYTHON ERROR\n{str(e)}"
def chat(self, user_message, max_tokens=200, temperature=0.7): if not user_message.strip(): return "⚠️ الرجاء كتابة رسالة." return self.send_to_model(user_message, max_tokens, temperature) def chat(self, msg, max_tokens, temp): if not msg.strip(): return "⚠️ اكتب رسالة" return self.send_to_model(msg, max_tokens, temp)
# ===============================# 🚀 إنشاء البوت# 🚀 Init# ===============================chatbot = AstramindChatbot()bot = AstramindChatbot()
# ===============================# 🎛️ Gradio Functions# 🎛️ UI# ===============================def respond(message, history, tokens, temp):def respond(msg, history, tokens, temp): history = history or [] reply = bot.chat(msg, tokens, temp) history.append((msg, reply)) return history, "", "✅ تم التنفيذ"
response = chatbot.chat(message, tokens, temp) history.append((message, response))
status = "✅ تم التنفيذ" if response.startswith("❌"): status = "🚨 حدث خطأ — راجع الرسالة"def clear(): bot.history = [] return [], "🗑️ تم المسح"
return history, "", statuswith gr.Blocks(title="Astramind") as demo: gr.Markdown("# 🤖 Astramind Chatbot")
def clear_chat(): chatbot.conversation_history = [] return [], "🗑️ تم مسح المحادثة" status = gr.Textbox("جاهز", interactive=False)
def welcome_message(): if HF_TOKEN: return f"🤖 Astramind Ready | Model: {MODEL_NAME}" return "⚠️ HF_TOKEN غير موجود في Secrets" chat_ui = gr.Chatbot(height=400)
# ===============================# 🖥️ Gradio UI# ===============================with gr.Blocks(title="Astramind Chatbot") as demo: gr.Markdown("# 🤖 Astramind") gr.Markdown("### مساعد دردشة عربي") with gr.Row(): msg = gr.Textbox(placeholder="اكتب رسالتك...", lines=2) send = gr.Button("إرسال")
status_box = gr.Textbox( value=welcome_message(), label="الحالة", interactive=False ) with gr.Accordion("⚙️ الإعدادات"): tokens = gr.Slider(50, 500, 200, step=10) temp = gr.Slider(0.1, 1.0, 0.7)
chatbot_ui = gr.Chatbot( label="المحادثة", height=400 ) send.click(respond, [msg, chat_ui, tokens, temp], [chat_ui, msg, status]) msg.submit(respond, [msg, chat_ui, tokens, temp], [chat_ui, msg, status])
with gr.Row(): message_input = gr.Textbox( placeholder="اكتب رسالتك هنا...", lines=2, scale=4 ) send_btn = gr.Button("إرسال", variant="primary") gr.Button("مسح").click(clear, outputs=[chat_ui, status])
with gr.Row(): clear_btn = gr.Button("مسح المحادثة") refresh_btn = gr.Button("🔄")
with gr.Accordion("⚙️ الإعدادات", open=False): max_tokens = gr.Slider(50, 500, value=200, step=10, label="طول الرد") temperature = gr.Slider(0.1, 1.0, value=0.7, step=0.1, label="الإبداعية")
gr.Examples( examples=[ ["السلام عليكم"], ["من أنت؟"], ["احكي لي عن نفسك"], ["كيف أتعلم الذكاء الاصطناعي؟"] ], inputs=message_input )
send_btn.click( respond, inputs=[message_input, chatbot_ui, max_tokens, temperature], outputs=[chatbot_ui, message_input, status_box] )
message_input.submit( respond, inputs=[message_input, chatbot_ui, max_tokens, temperature], outputs=[chatbot_ui, message_input, status_box] )
clear_btn.click( clear_chat, outputs=[chatbot_ui, status_box] )
refresh_btn.click( fn=welcome_message, outputs=status_box )
# ===============================# ▶️ Run# ===============================if __name__ == "__main__": demo.launch( server_name="0.0.0.0", server_port=7860, debug=True )demo.launch(server_name="0.0.0.0", server_port=7860, debug=True)app.py+62-152