kemo2018 commited on
Commit
a09dbe3
·
verified ·
1 Parent(s): 51de4b9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +187 -84
app.py CHANGED
@@ -1,115 +1,218 @@
1
  import gradio as gr
2
  import torch
3
- from transformers import pipeline, AutoTokenizer, AutoModelForCausalLM
4
- import sympy as sp
5
- from sympy import symbols, Eq, solve, diff, integrate
6
- from z3 import Solver, Int, sat
7
  import re
8
  import logging
9
  from collections import deque
10
-
11
- # ------------------- إعداد الـLogger -------------------
12
- logging.basicConfig(level=logging.INFO)
13
-
14
- # ------------------- تحميل نموذج خفيف (Phi-3 أو Gemma-2B) -------------------
15
- # نستخدم نموذج صغير يعمل على CPU بسرعة (أقل من 3 ثواني للرد)
16
- model_name = "microsoft/Phi-3-mini-4k-instruct" # 3.8B → يعمل ممتاز على Spaces CPU
17
- # بديل ممتاز: "google/gemma-2b-it"
18
-
19
- print("جاري تحميل النموذج... (مرة واحدة فقط)")
20
- tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
21
- model = AutoModelForCausalLM.from_pretrained(
22
- model_name,
23
- device_map="auto",
24
- torch_dtype=torch.float16,
25
- trust_remote_code=True,
26
- low_cpu_mem_usage=True
27
- )
28
- generator = pipeline("text-generation", model=model, tokenizer=tokenizer, max_new_tokens=150)
29
-
30
- # ------------------- ذاكرة السياق -------------------
31
- context = deque(maxlen=5)
32
-
33
- # ------------------- Math Solver (100% دقيق) -------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  def advanced_math_solver(question: str):
35
- x, y = symbols('x y')
 
 
36
  try:
37
- # حل المعادلات
38
- if "=" in question and ("حل" in question or "solve" in question.lower()):
39
- eq = question.split("=")
40
- if len(eq) == 2:
41
- left = sp.sympify(eq[0], locals={'x': x})
42
- right = sp.sympify(eq[1], locals={'x': x})
43
- sol = solve(Eq(left, right), x)
44
- return f"**الحل:** x = {sol}\n\n**الخطوات:**\n• المعادلة: {left} = {right}\n• الحل: {sol}"
45
-
46
- # اشتقاق
47
- elif any(k in question for k in ["اشتق", "مشتقة", "d/dx", "derivative"]):
48
- expr = re.search(r"اشتق\s+(.+)", question, re.I) or re.search(r"f'\(x\) = (.+)", question, re.I)
49
- if expr:
50
- f = sp.sympify(expr.group(1))
51
- deriv = diff(f, x)
52
- return f"**الدالة:** f(x) = {f}\n**المشتقة:** f'(x) = {deriv}"
53
-
54
- # تكامل
55
- elif any(k in question for k in ["تكامل", "integral", "∫"]):
56
- expr = re.search(r"تكامل\s+(.+)", question, re.I)
57
- if expr:
58
- f = sp.sympify(expr.group(1))
59
- integ = integrate(f, x)
60
- return f"**التكامل:** ∫{f} dx = {integ} + C"
61
-
62
- # حساب بسيط
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
63
  else:
64
- result = sp.sympify(question)
65
- return f"**النتيجة:** {result}"
 
 
 
 
 
66
 
67
  except Exception as e:
68
- return f"لم أتمكن من حلها رمزياً: {str(e)}"
69
-
70
- return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
- # ------------------- الرد الرئيسي -------------------
73
- def chat(message, history):
74
  global context
75
 
76
- # كشف المسائل الرياضية
77
- math_keywords = ["حل", "اشتق", "تكامل", "=", "x^", "sin", "cos", "log", "∫"]
78
- if any(k in message for k in math_keywords):
79
- math_answer = advanced_math_solver(message)
80
- if math_answer:
81
- context.append((message, math_answer))
82
- return math_answer
83
 
84
- # دردشة عادية باستخدام Phi-3
85
- messages = [{"role": "system", "content": "أنت مساعد ذكي عربي دقيق وأمين ومفيد."}]
86
- for user_msg, bot_msg in context:
87
- messages.append({"role": "user", "content": user_msg})
88
- messages.append({"role": "assistant", "content": bot_msg})
89
- messages.append({"role": "user", "content": message})
90
 
91
- output = generator(messages, do_sample=True, temperature=0.7, top_p=0.9)
92
- reply = output[0]["generated_text"][-1]["content"]
 
 
 
 
 
 
 
 
93
 
 
 
94
  context.append((message, reply))
95
  return reply
96
 
97
  # ------------------- واجهة Gradio -------------------
98
- with gr.Blocks(title="AGI Math Solver + Chat") as demo:
99
  gr.HTML("""
100
- <div style="text-align:center; padding:20px; background:#000; color:#00ff00; border-radius:15px;">
101
- <h1>AGI + حل رياضيات دقيق 100% + دردشة ذكية</h1>
102
- <p>اكتب أي مسألة رياضية أو سؤال عادي</p>
103
  </div>
104
  """)
105
 
106
  chatbot = gr.Chatbot(height=600)
107
- msg = gr.Textbox(label="أنت", placeholder="مثلاً: حل x² - 5x + 6 = 0 أو اشتق x³ + sin(x) أو مرحبا!")
 
 
 
 
108
  clear = gr.Button("مسح المحادثة")
109
 
110
- msg.submit(chat, [msg, chatbot], [msg, chatbot])
111
- clear.click(lambda: None, None, chatbot)
112
 
 
113
  demo.launch(
114
  share=True,
115
  server_name="0.0.0.0",
 
1
  import gradio as gr
2
  import torch
3
+ import math
 
 
 
4
  import re
5
  import logging
6
  from collections import deque
7
+ from transformers import GPT2Tokenizer, GPT2LMHeadModel
8
+ import sympy as sp
9
+ 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)),
27
+ "tan": lambda x: math.tan(math.radians(x)),
28
+ "sqrt": math.sqrt,
29
+ "log": math.log,
30
+ "exp": math.exp,
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.+-*/()**")
53
+ for c in expr:
54
+ if c not in allowed and not any(f in expr.lower() for f in SAFE_MATH):
55
+ return None
56
+ try:
57
+ result = eval(expr, {"__builtins__": {}}, SAFE_MATH)
58
+ if abs(result) > 1e12:
59
+ return None
60
+ return result
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:
77
+ eq_part = re.sub(r"[^=0-9xXyY\+\-\*/\^\(\)]", "", question)
78
+ if "=" in eq_part:
79
+ left, right = eq_part.split("=", 1)
80
+ x = symbols('x')
81
+ eq = Eq(sp.sympify(left), sp.sympify(right))
82
+ sol = solve(eq, x)
83
+ result["answer"] = sol
84
+ result["steps"] = [
85
+ f"المعادلة: {left} = {right}",
86
+ f"نقل الطرفين: {eq}",
87
+ f"الحل: x = {sol}"
88
+ ]
89
+ result["type"] = "algebra"
90
+ result["success"] = True
91
+ return result
92
+
93
+ elif any(kw in question for kw in ["اشتق", "مشتقة", "d/dx"]):
94
+ expr_match = re.search(r"اشتق\s+(.+)", question, re.I)
95
+ if expr_match:
96
+ expr = sp.sympify(expr_match.group(1))
97
+ x = symbols('x')
98
+ deriv = diff(expr, x)
99
+ result["answer"] = deriv
100
+ result["steps"] = [f"الدالة: f(x) = {expr}", f"المشتقة: f'(x) = {deriv}"]
101
+ result["type"] = "calculus"
102
+ result["success"] = True
103
+ return result
104
+
105
+ elif any(kw in question for kw in ["تكامل", "∫", "integral"]):
106
+ expr_match = re.search(r"تكامل\s+(.+)", question, re.I)
107
+ if expr_match:
108
+ expr = sp.sympify(expr_match.group(1))
109
+ x = symbols('x')
110
+ integ = integrate(expr, x)
111
+ result["answer"] = integ
112
+ result["steps"] = [f"الدالة: {expr}", f"التكامل: ∫{expr} dx = {integ} + C"]
113
+ result["type"] = "calculus"
114
+ result["success"] = True
115
+ return result
116
+
117
+ elif any(kw in question for kw in ["إذا", "فإن", "و", "أو"]):
118
+ s = Solver()
119
+ a, b = Int('a'), Int('b')
120
+ if "a أكبر من b" in question:
121
+ s.add(a > b)
122
+ if "a + b = 10" in question:
123
+ s.add(a + b == 10)
124
+ if s.check() == sat:
125
+ m = s.model()
126
+ result["answer"] = f"a = {m[a]}, b = {m[b]}"
127
+ result["steps"] = ["تم بناء النموذج المنطقي", "الحل موجود"]
128
+ result["success"] = True
129
+ result["type"] = "logic"
130
+ return result
131
+
132
  else:
133
+ calc = safe_eval(question)
134
+ if calc is not None:
135
+ result["answer"] = calc
136
+ result["steps"] = [f"حساب: {question} = {calc}"]
137
+ result["success"] = True
138
+ result["type"] = "basic"
139
+ return result
140
 
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:
151
+ prompt_lines.append(f"User: {u}\nAGI: {a}")
152
+ prompt_lines.append(f"User: {user_text}\nAGI:")
153
+ prompt = "\n".join(prompt_lines)
154
+
155
+ inputs = tokenizer.encode(prompt, return_tensors="pt", truncation=True, max_length=512)
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,
163
+ top_p=0.9,
164
+ top_k=50,
165
+ )
166
+ reply = tokenizer.decode(outputs[0], skip_special_tokens=True)
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
+ with gr.Blocks(title="AGI + حل رياضيات دقيق 100%") as demo:
197
  gr.HTML("""
198
+ <div style="text-align:center; padding:20px; background:#000; color:#0f0; border-radius:15px;">
199
+ <h1>AGI + حل رياضيات بدقة 100% + ذكاء عام</h1>
200
+ <p>اكتب أي شيء: مسألة رياضية أو سؤال عادي</p>
201
  </div>
202
  """)
203
 
204
  chatbot = gr.Chatbot(height=600)
205
+ msg = gr.Textbox(
206
+ label="أنت",
207
+ placeholder="مثال: حل x² - 5x + 6 = 0 أو اشتق sin(x) أو مرحبا!",
208
+ lines=2
209
+ )
210
  clear = gr.Button("مسح المحادثة")
211
 
212
+ msg.submit(chat_with_agi, [msg, chatbot], [msg, chatbot])
213
+ clear.click(lambda: None, None, chatbot, queue=False)
214
 
215
+ # ------------------- تشغيل التطبيق -------------------
216
  demo.launch(
217
  share=True,
218
  server_name="0.0.0.0",