kemo2018 commited on
Commit
c0617b2
·
verified ·
1 Parent(s): d89c159

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -88
app.py CHANGED
@@ -1,3 +1,8 @@
 
 
 
 
 
1
  import gradio as gr
2
  import torch
3
  import math
@@ -10,17 +15,17 @@ from sympy import symbols, Eq, solve, diff, integrate
10
  from z3 import Solver, Int, sat
11
  import traceback
12
 
13
- # ------------------- كل الكود الأصلي بدون أي تغيير -------------------
14
- # 1. Logging
15
- logging.basicConfig(level=logging.INFO) # في Spaces لا يمكن كتابة ملف، لكن logging يعمل في الـlogs
16
 
17
- # 2. Load GPT-2
18
- print("جاري تحميل GPT-2...")
19
- tokenizer = GPT2Tokenizer.from_pretrained("gpt2")
20
- model = GPT2LMHeadModel.from_pretrained("gpt2")
 
21
  model.eval()
22
 
23
- # 3. Safe math whitelist
24
  SAFE_MATH = {
25
  "sin": lambda x: math.sin(math.radians(x)),
26
  "cos": lambda x: math.cos(math.radians(x)),
@@ -31,22 +36,22 @@ SAFE_MATH = {
31
  "abs": abs,
32
  }
33
 
34
- # 4. Bad-word filter
35
  BAD_WORDS = {
36
  "كلب", "حمار", "غبي", "قذر", "بذيء", "حيوان", "نذل",
37
  "idiot", "stupid", "fuck", "shit", "damn", "hell"
38
  }
39
 
40
- # 5. Context memory
41
  context = deque(maxlen=3)
42
 
43
- # 6. Math pattern
44
  MATH_PATTERN = re.compile(r"[0-9+\-*/().^=]|sin|cos|tan|sqrt|log|exp|abs|تكامل|اشتق|حل", re.I)
45
 
46
  def is_math_expression(text: str) -> bool:
47
  return bool(MATH_PATTERN.search(text))
48
 
49
- # 7. Safe calculator
50
  def safe_eval(expr: str):
51
  expr = expr.strip().replace("^", "**").replace(" ", "")
52
  allowed = set("0123456789.+-*/()**")
@@ -61,16 +66,15 @@ def safe_eval(expr: str):
61
  except:
62
  return None
63
 
64
- # 8. Bad-word detection
65
  def contains_bad_word(text: str) -> bool:
66
  lowered = text.lower()
67
  return any(word in lowered for word in BAD_WORDS)
68
 
69
- # 9. Advanced Math Solver (كما هو بالضبط)
70
  def advanced_math_solver(question: str):
71
  question = question.strip()
72
  result = {"answer": None, "steps": [], "type": "unknown", "success": False}
73
-
74
  try:
75
  if any(op in question for op in ["=", "حل", "solve"]):
76
  if "x" in question or "y" in question:
@@ -141,10 +145,9 @@ def advanced_math_solver(question: str):
141
  except Exception as e:
142
  logging.error(f"Math solver error: {traceback.format_exc()}")
143
  result["steps"].append(f"خطأ داخلي: {str(e)}")
144
-
145
  return result
146
 
147
- # 10. GPT-2 generation (كما هو)
148
  def gpt2_reply(user_text: str) -> str:
149
  prompt_lines = []
150
  for u, a in context:
@@ -156,7 +159,7 @@ def gpt2_reply(user_text: str) -> str:
156
  with torch.no_grad():
157
  outputs = model.generate(
158
  inputs,
159
- max_length=inputs.shape[1] + 100,
160
  pad_token_id=tokenizer.eos_token_id,
161
  do_sample=True,
162
  temperature=0.7,
@@ -167,84 +170,56 @@ def gpt2_reply(user_text: str) -> str:
167
  reply = reply.split("AGI:")[-1].strip()
168
  return reply
169
 
170
- # ------------------- دالة Gradio الرئيسية (بدون تغيير المنطق) -------------------
171
- def chat_with_agi(message, history):
172
- global context
173
-
174
- logging.info(f"USER: {message}")
175
 
176
- if contains_bad_word(message):
177
- return "آسف، لا أقبل اللغة السيئة."
178
 
179
- if is_math_expression(message):
180
- math_result = advanced_math_solver(message)
 
 
 
181
  if math_result["success"]:
182
- answer = f"**الإجابة:** {math_result['answer']}\n\n"
183
  if math_result["steps"]:
184
- answer += "**الخطوات:**\n"
185
- for step in math_result["steps"]:
186
- answer += f"• {step}\n"
187
- context.append((message, str(math_result["answer"])))
188
- return answer
189
-
190
- # دردشة عادية بـ GPT-2
191
- reply = gpt2_reply(message)
192
- context.append((message, reply))
193
- return reply
194
 
195
- # ------------------- واجهة Gradio -------------------
196
- # ---------- واجهة Gradio مُصحَّحة 100% (زر إرسال + Enter يعمل) ----------
197
- # ---------- واجهة Gradio (مُصحَّحة: بدون submit_on_enter، مع زر واضح) ----------
198
- with gr.Blocks(title="AGI Math Solver + Chat") as demo:
 
 
 
199
  gr.HTML("""
200
- <div style="text-align:center; padding:20px; background:#000; color:#00ff00; border-radius:15px;">
201
- <h1>AGI + حل رياضيات دقيق 100% + دردشة ذكية</h1>
202
- <p>اكتب سؤالك واضغط Enter أو "إرسال"</p>
203
  </div>
204
  """)
205
-
206
- chatbot = gr.Chatbot(height=600)
207
-
208
- with gr.Row(): # وضع الـTextbox و الزر جنباً إلى جنب
209
- msg = gr.Textbox(
210
- label="أنت",
211
- placeholder="مثال: حل x² - 5x + 6 = 0 أو اشتق sin(x) أو مرحبا!",
212
- lines=2
213
- )
214
- send_btn = gr.Button("إرسال", variant="primary") # زر أخضر واضح
215
-
216
- clear = gr.Button("مسح المحادثة")
217
-
218
- def respond(message, history):
219
- if message is None or message.strip() == "":
220
- return "", history
221
- # منطقك الأصلي هنا (بدون تغيير)
222
- if contains_bad_word(message):
223
- reply = "آسف، لا أقبل اللغة السيئة."
224
- elif is_math_expression(message):
225
- math_result = advanced_math_solver(message)
226
- if math_result["success"]:
227
- reply = f"**الإجابة:** {math_result['answer']}\n\n**الخطوات:**\n" + "\n".join(f"• {step}" for step in math_result["steps"])
228
- context.append((message, str(math_result["answer"])))
229
- else:
230
- reply = "AGI: لم أتمكن من حلها رمزيًا، سأستخدم الذكاء العام...\n" + gpt2_reply(message)
231
- else:
232
- reply = gpt2_reply(message)
233
- context.append((message, reply))
234
-
235
- history.append([message, reply])
236
- return "", history
237
-
238
- # ربط Enter مع Textbox.submit()
239
- msg.submit(respond, [msg, chatbot], [msg, chatbot])
240
-
241
- # ربط الزر مع button.click()
242
- send_btn.click(respond, [msg, chatbot], [msg, chatbot])
243
-
244
- # مسح المحادثة
245
- clear.click(lambda: None, None, chatbot, queue=False)
246
-
247
- # تشغيل التطبيق
248
  demo.launch(
249
  share=True,
250
  server_name="0.0.0.0",
 
1
+ # ------------------------------------------------------------
2
+ # AGI + Safe Math + 100% Accurate Math Solver – Terminal Style
3
+ # يعمل مثل سطر الأوامر تماماً على Hugging Face Spaces
4
+ # ------------------------------------------------------------
5
+
6
  import gradio as gr
7
  import torch
8
  import math
 
15
  from z3 import Solver, Int, sat
16
  import traceback
17
 
18
+ # ---------- 1. Logging ----------
19
+ logging.basicConfig(level=logging.INFO)
 
20
 
21
+ # ---------- 2. Load GPT-2 ----------
22
+ model_name = "gpt2"
23
+ print("جاري تحميل GPT-2... (مرة واحدة فقط)")
24
+ tokenizer = GPT2Tokenizer.from_pretrained(model_name)
25
+ model = GPT2LMHeadModel.from_pretrained(model_name)
26
  model.eval()
27
 
28
+ # ---------- 3. Safe math whitelist ----------
29
  SAFE_MATH = {
30
  "sin": lambda x: math.sin(math.radians(x)),
31
  "cos": lambda x: math.cos(math.radians(x)),
 
36
  "abs": abs,
37
  }
38
 
39
+ # ---------- 4. Bad-word filter ----------
40
  BAD_WORDS = {
41
  "كلب", "حمار", "غبي", "قذر", "بذيء", "حيوان", "نذل",
42
  "idiot", "stupid", "fuck", "shit", "damn", "hell"
43
  }
44
 
45
+ # ---------- 5. Context memory (last 3 turns) ----------
46
  context = deque(maxlen=3)
47
 
48
+ # ---------- 6. Math pattern ----------
49
  MATH_PATTERN = re.compile(r"[0-9+\-*/().^=]|sin|cos|tan|sqrt|log|exp|abs|تكامل|اشتق|حل", re.I)
50
 
51
  def is_math_expression(text: str) -> bool:
52
  return bool(MATH_PATTERN.search(text))
53
 
54
+ # ---------- 7. Safe calculator ----------
55
  def safe_eval(expr: str):
56
  expr = expr.strip().replace("^", "**").replace(" ", "")
57
  allowed = set("0123456789.+-*/()**")
 
66
  except:
67
  return None
68
 
69
+ # ---------- 8. Bad-word detection ----------
70
  def contains_bad_word(text: str) -> bool:
71
  lowered = text.lower()
72
  return any(word in lowered for word in BAD_WORDS)
73
 
74
+ # ---------- 9. Advanced Math Solver (كما كتبته أنت بالضبط) ----------
75
  def advanced_math_solver(question: str):
76
  question = question.strip()
77
  result = {"answer": None, "steps": [], "type": "unknown", "success": False}
 
78
  try:
79
  if any(op in question for op in ["=", "حل", "solve"]):
80
  if "x" in question or "y" in question:
 
145
  except Exception as e:
146
  logging.error(f"Math solver error: {traceback.format_exc()}")
147
  result["steps"].append(f"خطأ داخلي: {str(e)}")
 
148
  return result
149
 
150
+ # ---------- 10. GPT-2 generation ----------
151
  def gpt2_reply(user_text: str) -> str:
152
  prompt_lines = []
153
  for u, a in context:
 
159
  with torch.no_grad():
160
  outputs = model.generate(
161
  inputs,
162
+ max_length=inputs.shape[1] + 120,
163
  pad_token_id=tokenizer.eos_token_id,
164
  do_sample=True,
165
  temperature=0.7,
 
170
  reply = reply.split("AGI:")[-1].strip()
171
  return reply
172
 
173
+ # ---------- 11. Terminal-style Interface ----------
174
+ def terminal_input(user_input, history):
175
+ if not user_input.strip():
176
+ return history + [[f"<span style='color:#00ff00'>أنت:</span> ", ""]], ""
 
177
 
178
+ # إضافة السؤال
179
+ history.append([f"<span style='color:#00ff00'>أنت:</span> {user_input}", None])
180
 
181
+ # المعالجة
182
+ if contains_bad_word(user_input):
183
+ reply = "آسف، لا أقبل اللغة السيئة."
184
+ elif is_math_expression(user_input):
185
+ math_result = advanced_math_solver(user_input)
186
  if math_result["success"]:
187
+ reply = f"<span style='color:#ffff00'><strong>الإجابة:</strong></span> {math_result['answer']}\n"
188
  if math_result["steps"]:
189
+ reply += "<span style='color:#8888ff'>الخطوات:</span>\n" + "\n".join(f" • {s}" for s in math_result["steps"])
190
+ context.append((user_input, str(math_result["answer"])))
191
+ else:
192
+ reply = "لم أتمكن من حلها رمزيًا، سأستخدم الذكاء العام...\n" + gpt2_reply(user_input)
193
+ else:
194
+ reply = gpt2_reply(user_input)
195
+ context.append((user_input, reply))
196
+
197
+ # إضافة الرد
198
+ history.append([None, f"<span style='color:#00ffff'>AGI:</span> {reply}"])
199
 
200
+ return history, "" # امسح الإدخال بعد الإرسال
201
+
202
+ # ---------- Gradio Terminal UI ----------
203
+ with gr.Blocks(css="""
204
+ .container {background: black; color: #00ff00; font-family: 'Courier New', monospace;}
205
+ .output {white-space: pre-wrap;}
206
+ """, title="AGI Terminal") as demo:
207
  gr.HTML("""
208
+ <div style="text-align:center;background:#000;color:#0f0;padding:20px;font-size:24px;">
209
+ <strong>AGI + حل رياضيات دقيق 100% – وضع Terminal</strong>
 
210
  </div>
211
  """)
212
+
213
+ chat_history = gr.HTML() # نستخدم HTML للتحكم الكامل في الشكل
214
+
215
+ input_box = gr.Textbox(
216
+ label="",
217
+ placeholder="اكتب أي شيء هنا ثم اضغط Enter... (مثال: حل x²-5x+6=0)",
218
+ lines=1
219
+ )
220
+
221
+ input_box.submit(terminal_input, [input_box, chat_history], [chat_history, input_box])
222
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
223
  demo.launch(
224
  share=True,
225
  server_name="0.0.0.0",