Update app.py
Browse files
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 |
-
|
| 15 |
-
logging.basicConfig(level=logging.INFO) # في Spaces لا يمكن كتابة ملف، لكن logging يعمل في الـlogs
|
| 16 |
|
| 17 |
-
# 2. Load GPT-2
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
| 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] +
|
| 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 |
-
# ----------
|
| 171 |
-
def
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
logging.info(f"USER: {message}")
|
| 175 |
|
| 176 |
-
|
| 177 |
-
|
| 178 |
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
|
|
|
| 181 |
if math_result["success"]:
|
| 182 |
-
|
| 183 |
if math_result["steps"]:
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
|
| 195 |
-
#
|
| 196 |
-
|
| 197 |
-
# ----------
|
| 198 |
-
with gr.Blocks(
|
|
|
|
|
|
|
|
|
|
| 199 |
gr.HTML("""
|
| 200 |
-
<div style="text-align:center;
|
| 201 |
-
<
|
| 202 |
-
<p>اكتب سؤالك واضغط Enter أو "إرسال"</p>
|
| 203 |
</div>
|
| 204 |
""")
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 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",
|