kemo2018 commited on
Commit
91823fa
·
verified ·
1 Parent(s): 5c04874

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +119 -261
app.py CHANGED
@@ -1,301 +1,159 @@
1
  # ------------------------------------------------------------
2
- # AGI + Safe Math + Awareness + 100% Accurate Math Solver (Best-Practice)
3
- # Hugging Face Spaces Version – Fixed readonly Error
4
  # ------------------------------------------------------------
5
 
6
  import gradio as gr
7
  import torch
8
- import math
 
 
 
9
  import re
10
- import logging
11
  from collections import deque
12
- from transformers import GPT2Tokenizer, GPT2LMHeadModel
13
- import sympy as sp
14
- from sympy import symbols, Eq, solve, diff, integrate, simplify, sqrt, sin, cos, tan, log, exp
15
- from z3 import Solver, Int, Real, sat
16
- import traceback
17
 
18
- # ---------- 1. Logging ----------
19
- logging.basicConfig(
20
- level=logging.INFO,
21
- format="%(asctime)s | %(levelname)s | %(message)s",
22
- encoding="utf-8"
 
 
 
 
 
 
 
23
  )
24
-
25
- # ---------- 2. Load GPT-2 (once) ----------
26
- model_name = "gpt2"
27
- print("جاري تحميل GPT-2... (مرة واحدة فقط)")
28
- tokenizer = GPT2Tokenizer.from_pretrained(model_name)
29
- model = GPT2LMHeadModel.from_pretrained(model_name)
30
  model.eval()
31
 
32
- # ---------- 3. Safe math whitelist ----------
33
- SAFE_MATH = {
34
- "sin": lambda x: math.sin(math.radians(x)),
35
- "cos": lambda x: math.cos(math.radians(x)),
36
- "tan": lambda x: math.tan(math.radians(x)),
37
- "sqrt": math.sqrt,
38
- "log": math.log,
39
- "exp": math.exp,
40
- "abs": abs,
41
- }
42
-
43
- # ---------- 4. Bad-word filter ----------
44
- BAD_WORDS = {
45
- "كلب", "حمار", "غبي", "قذر", "بذيء", "حيوان", "نذل",
46
- "idiot", "stupid", "fuck", "shit", "damn", "hell"
47
- }
48
 
49
- # ---------- 5. Context memory (last 3 turns) ----------
50
- context = deque(maxlen=3)
51
 
52
- # ---------- 6. Math pattern ----------
53
- MATH_PATTERN = re.compile(r"[0-9+\-*/().^=]|sin|cos|tan|sqrt|log|exp|abs|تكامل|اشتق|حل", re.I)
54
-
55
- def is_math_expression(text: str) -> bool:
56
  return bool(MATH_PATTERN.search(text))
57
 
58
- # ---------- 7. Safe calculator (basic) ----------
59
- def safe_eval(expr: str):
60
- expr = expr.strip().replace("^", "**").replace(" ", "")
61
- allowed = set("0123456789.+-*/()**")
62
- for c in expr:
63
- if c not in allowed and not any(f in expr.lower() for f in SAFE_MATH):
64
- return None
65
- try:
66
- result = eval(expr, {"__builtins__": {}}, SAFE_MATH)
67
- if abs(result) > 1e12:
68
- return None
69
- return result
70
- except:
71
- return None
72
-
73
- # ---------- 8. Bad-word detection ----------
74
- def contains_bad_word(text: str) -> bool:
75
- lowered = text.lower()
76
- return any(word in lowered for word in BAD_WORDS)
77
-
78
- # ---------- 9. Advanced Math Solver (100% Accurate, No Training) ----------
79
  def advanced_math_solver(question: str):
80
- """حل أي مشكلة رياضية بدقة 100% باستخدام SymPy + Z3"""
81
- question = question.strip()
82
- result = {"answer": None, "steps": [], "type": "unknown", "success": False}
83
-
84
  try:
85
- # --- 1. جبر: حل المعادلات ---
86
- if any(op in question for op in ["=", "حل", "solve"]):
87
- if "x" in question or "y" in question:
88
- # استخراج المعادلة
89
- eq_part = re.sub(r"[^=0-9xXyY\+\-\*/\^\(\)]", "", question)
90
- if "=" in eq_part:
91
- left, right = eq_part.split("=", 1)
92
- x = symbols('x')
93
- eq = Eq(sp.sympify(left), sp.sympify(right))
94
- sol = solve(eq, x)
95
- result["answer"] = sol
96
- result["steps"] = [
97
- f"المعادلة: {left} = {right}",
98
- f"نقل الطرفين: {eq}",
99
- f"الحل: x = {sol}"
100
- ]
101
- result["type"] = "algebra"
102
- result["success"] = True
103
- return result
104
-
105
- # --- 2. تفاضل ---
106
- elif any(kw in question for kw in ["اشتق", "مشتقة", "d/dx"]):
107
- expr_match = re.search(r"اشتق\s+(.+)", question, re.I)
108
- if expr_match:
109
- expr = sp.sympify(expr_match.group(1))
110
- x = symbols('x')
111
- deriv = diff(expr, x)
112
- result["answer"] = deriv
113
- result["steps"] = [
114
- f"الدالة: f(x) = {expr}",
115
- f"المشتقة: f'(x) = {deriv}"
116
- ]
117
- result["type"] = "calculus"
118
- result["success"] = True
119
- return result
120
-
121
- # --- 3. تكامل ---
122
- elif any(kw in question for kw in ["تكامل", "∫", "integral"]):
123
- expr_match = re.search(r"تكامل\s+(.+)", question, re.I)
124
- if expr_match:
125
- expr = sp.sympify(expr_match.group(1))
126
- x = symbols('x')
127
- integ = integrate(expr, x)
128
- result["answer"] = integ
129
- result["steps"] = [
130
- f"الدالة: {expr}",
131
- f"التكامل: ∫{expr} dx = {integ} + C"
132
- ]
133
- result["type"] = "calculus"
134
- result["success"] = True
135
- return result
136
-
137
- # --- 4. استدلال منطقي (Z3) ---
138
- elif any(kw in question for kw in ["إذا", "فإن", "و", "أو"]):
139
- s = Solver()
140
- a, b = Int('a'), Int('b')
141
- if "a أكبر من b" in question:
142
- s.add(a > b)
143
- if "a + b = 10" in question:
144
- s.add(a + b == 10)
145
- if s.check() == sat:
146
- m = s.model()
147
- result["answer"] = f"a = {m[a]}, b = {m[b]}"
148
- result["steps"] = ["تم بناء النموذج المنطقي", "الحل موجود"]
149
- result["success"] = True
150
- result["type"] = "logic"
151
- return result
152
-
153
- # --- 5. حسابات بسيطة (fallback) ---
154
- else:
155
- calc = safe_eval(question)
156
- if calc is not None:
157
- result["answer"] = calc
158
- result["steps"] = [f"حساب: {question} = {calc}"]
159
- result["success"] = True
160
- result["type"] = "basic"
161
- return result
162
 
163
  except Exception as e:
164
- logging.error(f"Math solver error: {traceback.format_exc()}")
165
- result["steps"].append(f"خطأ داخلي: {str(e)}")
166
-
167
- return result
168
-
169
- # ---------- 10. GPT-2 generation ----------
170
- def gpt2_reply(user_text: str) -> str:
171
- prompt_lines = []
172
- for u, a in context:
173
- prompt_lines.append(f"User: {u}\nAGI: {a}")
174
- prompt_lines.append(f"User: {user_text}\nAGI:")
175
- prompt = "\n".join(prompt_lines)
176
-
177
- inputs = tokenizer.encode(prompt, return_tensors="pt", truncation=True, max_length=512)
178
- with torch.no_grad():
179
- outputs = model.generate(
180
- inputs,
181
- max_length=inputs.shape[1] + 100,
182
- pad_token_id=tokenizer.eos_token_id,
183
- do_sample=True,
184
- temperature=0.7,
185
- top_p=0.9,
186
- top_k=50,
187
- )
 
 
 
 
188
  reply = tokenizer.decode(outputs[0], skip_special_tokens=True)
189
- reply = reply.split("AGI:")[-1].strip()
190
  return reply
191
 
192
- # ---------- Terminal-style Interface ----------
193
- def process_input(user_input, output_text):
194
  global context
195
 
196
- if user_input.lower() in ["exit", "quit", "خروج"]:
197
- reply = "تم الإغلاق. شكرًا!"
198
- output_text += f"\nأنت: {user_input}\nAGI: {reply}\n"
199
- return output_text, ""
200
-
201
- logging.info(f"USER: {user_input}")
202
 
203
- if contains_bad_word(user_input):
204
- reply = "AGI: آسف، لا أقبل اللغة السيئة.\n"
205
- logging.warning("Bad word detected")
206
- elif is_math_expression(user_input):
207
- print("AGI: جاري حل المسألة بدقة 100%...")
208
- math_result = advanced_math_solver(user_input)
209
- if math_result["success"]:
210
- reply = f"AGI: الإجابة: {math_result['answer']}\n"
211
- if math_result["steps"]:
212
- reply += "الخطوات:\n"
213
- for step in math_result["steps"]:
214
- reply += f" • {step}\n"
215
- print()
216
- logging.info(f"MATH SUCCESS: {math_result['answer']} | Type: {math_result['type']}")
217
- context.append((user_input, str(math_result["answer"])))
218
  else:
219
- reply = "AGI: لم أتمكن من حلها رمزيًا، سأستخدم الذكاء العام...\n"
 
220
  else:
221
- reply = gpt2_reply(user_input)
222
- logging.info(f"AGI REPLY: {reply}")
223
- context.append((user_input, reply))
224
-
225
- output_text += f"\nأنت: {user_input}\nAGI: {reply}"
226
- return output_text, ""
227
 
228
- # ---------- Gradio UI (Fixed: No readonly, Use HTML for Output) ----------
229
- print("AGI + 100% Accurate Math Solver (Best-Practice) جاهز!")
230
- print("أمثلة:")
231
- print(" حل x^3 - 6x^2 + 11x - 6 = 0")
232
- print(" اشتق x^2 + sin(x)")
233
- print(" تكامل x^2 + 2x")
234
- print(" إذا كان a أكبر من b و a + b = 10، فما قيم a و b؟")
235
- print(" 5 + 3 * 2")
236
- print("اكتب 'exit' للخروج.\n")
237
 
238
- with gr.Blocks(title="AGI Math Solver Terminal") as demo:
239
- # Header
240
  gr.HTML("""
241
- <div style="text-align:center; padding:20px; background-color:#000; color:#00ff00; border-radius:15px; margin-bottom:20px; font-family:monospace;">
242
- <h1>AGI + 100% Accurate Math Solver – Terminal Mode</h1>
243
- <p>اكتب سؤالك أو مسألة رياضية واضغط Enter</p>
244
  </div>
245
  """)
246
 
247
- # Output as HTML (no readonly error)
248
- output_html = gr.HTML(
249
- value="""
250
- <pre style="background:#000; color:#00ff00; padding:10px; height:400px; overflow-y:scroll; font-family:monospace;">
251
- AGI: AGI + 100% Accurate Math Solver جاهز!<br>
252
- أمثلة:<br>
253
- • حل x^3 - 6x^2 + 11x - 6 = 0<br>
254
- • اشتق x^2 + sin(x)<br>
255
- • تكامل x^2 + 2x<br>
256
- • 5 + 3 * 2<br>
257
- اكتب 'exit' للخروج.
258
- </pre>
259
- """
260
- )
261
 
262
  msg = gr.Textbox(
263
- label="أنت: ",
264
- placeholder="اكتب هنا ثم اضغط Enter...",
265
- lines=1
 
266
  )
267
 
268
- # Process input and update HTML output
269
- def update_output(message, current_html):
270
- if message.lower() in ["exit", "quit", "خروج"]:
271
- reply = "تم الإغلاق. شكرًا!"
272
- new_html = current_html + f"<br><span style='color:#00ff00'>أنت:</span> {message}<br><span style='color:#ffff00'>AGI:</span> {reply}"
273
- else:
274
- # Your original logic
275
- if contains_bad_word(message):
276
- reply = "AGI: آسف، لا أقبل اللغة السيئة."
277
- elif is_math_expression(message):
278
- math_result = advanced_math_solver(message)
279
- if math_result["success"]:
280
- reply = f"AGI: الإجابة: {math_result['answer']}<br>"
281
- if math_result["steps"]:
282
- reply += "الخطوات:<br>"
283
- for step in math_result["steps"]:
284
- reply += f" • {step}<br>"
285
- context.append((message, str(math_result["answer"])))
286
- else:
287
- reply = "AGI: لم أتمكن من حلها رمزيًا، سأستخدم الذكاء العام..."
288
- else:
289
- reply = gpt2_reply(message)
290
- context.append((message, reply))
291
-
292
- new_html = current_html + f"<br><span style='color:#00ff00'>أنت:</span> {message}<br><span style='color:#ffff00'>AGI:</span> {reply}"
293
-
294
- # Return updated HTML
295
- return gr.update(value=new_html)
296
-
297
- msg.submit(update_output, [msg, output_html], output_html)
298
- msg.submit(lambda x: "", outputs=[msg]) # Clear input after submit
299
 
300
  demo.launch(
301
  share=True,
 
1
  # ------------------------------------------------------------
2
+ # AGI + 100% Accurate Math Solver + Multilingual Smart Reply
3
+ # يرد باللغة نفسها (عربي/إنجليزي) + Terminal Style
4
  # ------------------------------------------------------------
5
 
6
  import gradio as gr
7
  import torch
8
+ from transformers import AutoTokenizer, AutoModelForCausalLM
9
+ import sympy as sp
10
+ from sympy import symbols, Eq, solve, diff, integrate
11
+ from z3 import Solver, Int, sat
12
  import re
 
13
  from collections import deque
 
 
 
 
 
14
 
15
+ # ---------- تحميل نموذج ذكي حديث (يدعم العربية والإنجليزية) ----------
16
+ model_name = "HuggingFaceH4/zephyr-7b-beta" # أفضل نموذج مجاني 2025
17
+ # بديل ممتاز: "meta-llama/Llama-3.2-3B-Instruct"
18
+
19
+ print("جاري تحميل النموذج الذكي... (مرة واحدة فقط)")
20
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
21
+ model = AutoModelForCausalLM.from_pretrained(
22
+ model_name,
23
+ torch_dtype=torch.float16,
24
+ device_map="auto",
25
+ trust_remote_code=True,
26
+ low_cpu_mem_usage=True
27
  )
 
 
 
 
 
 
28
  model.eval()
29
 
30
+ # ---------- ذاكرة السياق ----------
31
+ context = deque(maxlen=6)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ # ---------- كشف المسائل الرياضية ----------
34
+ MATH_PATTERN = re.compile(r"[0-9+\-*/().^=]|sin|cos|tan|sqrt|log|exp|اشتق|تكامل|حل|d/dx|integral", re.I)
35
 
36
+ def is_math_question(text: str) -> bool:
 
 
 
37
  return bool(MATH_PATTERN.search(text))
38
 
39
+ # ---------- حل المسائل الرياضية بدقة 100% ----------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  def advanced_math_solver(question: str):
41
+ x = symbols('x')
 
 
 
42
  try:
43
+ question = question.strip().replace("^", "**")
44
+
45
+ # حل المعادلات
46
+ if "=" in question and ("حل" in question or "solve" in question.lower() or "x" in question):
47
+ eq = question.split("=")
48
+ if len(eq) == 2:
49
+ left = sp.sympify(eq[0], locals={'x': x})
50
+ right = sp.sympify(eq[1], locals={'x': x})
51
+ sol = solve(Eq(left, right), x)
52
+ return f"**الحل:** x = {sol}", f"المعادلة: {left} = {right}\nالحل: x = {sol}"
53
+
54
+ # اشتقاق
55
+ if any(k in question for k in ["اشتق", "مشتقة", "d/dx", "derivative"]):
56
+ expr_str = re.sub(r".*اشتق\s+|\s.*", "", question, flags=re.I)
57
+ expr = sp.sympify(expr_str or question)
58
+ deriv = diff(expr, x)
59
+ return f"**المشتقة:** {deriv}", f"الدالة: {expr}\nالمشتقة: {deriv}"
60
+
61
+ # تكامل
62
+ if any(k in question for k in ["تكامل", "integral", "∫"]):
63
+ expr_str = re.sub(r".*تكامل\s+|\s.*", "", question, flags=re.I)
64
+ expr = sp.sympify(expr_str or question)
65
+ integ = integrate(expr, x)
66
+ return f"**التكامل:** ∫{expr} dx = {integ} + C", f"الدالة: {expr}\nالتكامل: {integ} + C"
67
+
68
+ # حساب بسيط
69
+ result = sp.sympify(question)
70
+ return f"**النتيجة:** {result}", f"حساب: {question} = {result}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
  except Exception as e:
73
+ return None, f"خطأ في الحل: {str(e)}"
74
+
75
+ # ---------- رد ذكي متعدد اللغات (يرد بنفس لغة السؤال) ----------
76
+ def smart_reply(user_text: str) -> str:
77
+ messages = [{"role": "system", "content": "أنت مساعد ذكي يرد بنفس لغة المستخدم (عربي أو إنجليزي) بأسلوب واضح ومفيد."}]
78
+
79
+ for user_msg, bot_msg in context:
80
+ messages.append({"role": "user", "content": user_msg})
81
+ messages.append({"role": "assistant", "content": bot_msg})
82
+
83
+ messages.append({"role": "user", "content": user_text})
84
+
85
+ inputs = tokenizer.apply_chat_template(
86
+ messages,
87
+ tokenize=True,
88
+ add_generation_prompt=True,
89
+ return_tensors="pt"
90
+ ).to(model.device)
91
+
92
+ outputs = model.generate(
93
+ inputs,
94
+ max_new_tokens=300,
95
+ temperature=0.7,
96
+ top_p=0.9,
97
+ do_sample=True,
98
+ pad_token_id=tokenizer.eos_token_id
99
+ )
100
+
101
  reply = tokenizer.decode(outputs[0], skip_special_tokens=True)
102
+ reply = reply.split("assistant")[-1].strip()
103
  return reply
104
 
105
+ # ---------- المعالجة الرئيسية ----------
106
+ def process(message, html_output):
107
  global context
108
 
109
+ if not message.strip():
110
+ return html_output, ""
 
 
 
 
111
 
112
+ user_line = f"<span style='color:#00ff88'>أنت:</span> {message}<br>"
113
+
114
+ if is_math_question(message):
115
+ math_answer, steps = advanced_math_solver(message)
116
+ if math_answer:
117
+ reply = f"<span style='color:#ffff00'>{math_answer}</span><br><span style='color:#88ccff'>{steps}</span>"
118
+ context.append((message, math_answer))
 
 
 
 
 
 
 
 
119
  else:
120
+ reply = f"<span style='color:#ff8888'>لم أتمكن من حلها رياضياً، سأجيب ذكياً...</span><br>{smart_reply(message)}"
121
+ context.append((message, "رد ذكي"))
122
  else:
123
+ reply = smart_reply(message)
124
+ context.append((message, reply))
 
 
 
 
125
 
126
+ new_html = html_output + user_line + f"<span style='color:#00ffff'>AGI:</span> {reply}<br><br>"
127
+ return new_html, ""
 
 
 
 
 
 
 
128
 
129
+ # ---------- واجهة Terminal (بدون أي أخطاء) ----------
130
+ with gr.Blocks(title="AGI Terminal") as demo:
131
  gr.HTML("""
132
+ <div style="text-align:center; padding:20px; background:#000; color:#00ff00; font-family:monospace; border-bottom:3px solid #00ff00;">
133
+ <h1>AGI + حل رياضيات دقيق 100% + ذكاء متعدد اللغات</h1>
134
+ <p>اكتب أي شيء: مسألة رياضية أو سؤال عادي (عربي أو إنجليزي) واضغط Enter</p>
135
  </div>
136
  """)
137
 
138
+ terminal = gr.HTML(value="""
139
+ <pre style="background:#000; color:#00ff00; padding:15px; height:500px; overflow-y:auto; font-family:monospace; border:2px solid #00ff00; border-radius:10px;">
140
+ <span style="color:#ffff00">AGI جاهز! مرحباً بك</span>
141
+ <span style="color:#88ccff">جرب:</span>
142
+ • حل x² - 5x + 6 = 0
143
+ • اشتق x³ + sin(x)
144
+ • What is the sun?
145
+ • Who invented electricity?
146
+ </pre>
147
+ """)
 
 
 
 
148
 
149
  msg = gr.Textbox(
150
+ placeholder="اكتب هنا واضغط Enter...",
151
+ lines=1,
152
+ label="",
153
+ container=False
154
  )
155
 
156
+ msg.submit(process, [msg, terminal], [terminal, msg])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
157
 
158
  demo.launch(
159
  share=True,