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