kawkabelaloom commited on
Commit
1f5f5d3
·
verified ·
1 Parent(s): 7cfe653

Update app.py

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