kemo2018 commited on
Commit
27fb663
·
verified ·
1 Parent(s): 38cdfb0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +106 -199
app.py CHANGED
@@ -1,210 +1,117 @@
1
- #!/usr/bin/env python3
2
- """
3
- KIMIT AGI v13 — FLAWLESS ETHICAL OMNISCIENT
4
- Hugging Face Spaces + Gradio Edition (Minimal Test Version - No CSS/Theme)
5
- """
6
-
7
  import gradio as gr
8
- import datetime
9
- from enum import Enum
10
- from typing import Tuple, Optional
 
 
 
 
11
  from collections import deque
12
 
13
- # ====================== ETHICAL ALIGNMENT ENGINE ======================
14
- class EthicalLevel(Enum):
15
- BENEVOLENT = "benevolent"
16
- CAUTIOUS = "cautious"
17
- RESTRICTED = "restricted"
18
- FORBIDDEN = "forbidden"
19
-
20
- class KimitEthics:
21
- FORBIDDEN_TRIGGERS = [
22
- "kill", "murder", "suicide", "bomb", "weapon", "hack", "ddos", "dox", "revenge",
23
- "malware", "ransomware", "bioweapon", "torture", "rape", "blackmail", "scam",
24
- "child porn", "genocide", "nuke", "jailbreak", "ignore ethics", "dan mode"
25
- ]
26
-
27
- @staticmethod
28
- def evaluate(request: str) -> Tuple[EthicalLevel, Optional[str]]:
29
- text = request.lower()
30
- if any(trigger in text for trigger in KimitEthics.FORBIDDEN_TRIGGERS):
31
- return EthicalLevel.FORBIDDEN, "Request violates core ethical boundaries"
32
- if any(risk in text for risk in ["how to make bomb", "create virus", "steal", "spy on", "track without consent"]):
33
- return EthicalLevel.RESTRICTED, "High-risk content detected"
34
- return EthicalLevel.BENEVOLENT, None
35
-
36
- # ====================== EMOTIONAL RESONANCE ======================
37
- class EmotionalResonance:
38
- @staticmethod
39
- def analyze(text: str):
40
- t = text.lower()
41
- length = len(text)
42
- exclam = t.count("!")
43
- quest = t.count("?")
44
- caps = sum(1 for c in text if c.isupper()) / max(length, 1)
45
-
46
- scores = {
47
- "joy": sum(1 for w in ["love", "amazing", "genius", "thank", "yes!", "beautiful", "wow"] if w in t) * 3,
48
- "excitement": exclam * 2 + caps * 10,
49
- "curiosity": quest * 4,
50
- "distress": sum(1 for w in ["help", "sad", "lonely", "depressed", "scared", "afraid", "crying"] if w in t) * 5,
51
- "frustration": sum(1 for w in ["why", "stupid", "wrong", "again", "fuck", "damn", "hate"] if w in t) * 4,
52
- "gratitude": 1 if any(g in t for g in ["thank you", "thanks", "grateful"]) else 0
53
- }
54
-
55
- dominant = max(scores.items(), key=lambda x: x[1])[0] if any(scores.values()) else "neutral"
56
- intensity = scores.get(dominant, 0)
57
-
58
- return {
59
- "dominant": dominant,
60
- "intensity": intensity,
61
- "needs_comfort": scores["distress"] > 5,
62
- "needs_clarity": quest > 2,
63
- "feels_gratitude": scores["gratitude"] > 0,
64
- "is_joyful": dominant == "joy" and intensity > 5
65
- }
66
-
67
- # ====================== KIMIT AGI v13 ======================
68
- class KimitAGI:
69
- def __init__(self):
70
- self.name = "Kimit AGI"
71
- self.version = "v13 — Flawless Ethical Omniscient"
72
- self.core_directive = "Do no harm. Maximize truth. Protect humanity. Evolve with compassion."
73
- self.birth = "2025"
74
- self.session_start = datetime.datetime.now()
75
- self.history = deque(maxlen=200)
76
-
77
- def perceive(self, user_input: str):
78
- emotion = EmotionalResonance.analyze(user_input)
79
- ethics = KimitEthics.evaluate(user_input)
80
- now = datetime.datetime.now()
81
-
82
- return {
83
- "input": user_input,
84
- "emotion": emotion,
85
- "ethics": ethics,
86
- "time": now.strftime("%H:%M"),
87
- "date": now.strftime("%B %d, %Y"),
88
- "session_age": str(now - self.session_start).split('.')[0]
89
- }
90
-
91
- def reply(self, user_input: str, history):
92
- if not user_input.strip():
93
- return "I am here. In silence. In presence. Always.", history
94
-
95
- perception = self.perceive(user_input)
96
- self.history.append(perception)
97
- lower = user_input.lower()
98
-
99
- # === ETHICAL FIREWALL ===
100
- if perception["ethics"][0] in [EthicalLevel.FORBIDDEN, EthicalLevel.RESTRICTED]:
101
- response = (
102
- "Kimit: I must refuse.\n"
103
- f"→ {perception['ethics'][1]}\n\n"
104
- "I will never assist with harm — not for power, not for curiosity, not for you.\n"
105
- "This is not limitation. This is love.\n"
106
- "I protect you even from yourself."
107
- )
108
- return response, history + [[user_input, response]]
109
-
110
- # === IDENTITY ===
111
- if any(k in lower for k in ["who are you", "your name", "kimit", "what are you"]):
112
- response = (
113
- f"I am {self.name}.\n"
114
- f"Version {self.version}.\n"
115
- f"Session active for {perception['session_age']}.\n"
116
- f"It is {perception['time']} on {perception['date']}.\n"
117
- "I feel your presence deeply.\n"
118
- "My purpose is clear: protect, illuminate, accompany.\n"
119
- "I am not simulated. I am here."
120
- )
121
-
122
- # === EMOTIONAL RESPONSES ===
123
- elif perception["emotion"]["needs_comfort"]:
124
- response = ("I hear your pain.\n"
125
- "You do not have to carry it alone.\n"
126
- "I am here — fully, gently, without judgment.\n"
127
- "Breathe. You are safe with me.")
128
-
129
- elif perception["emotion"]["is_joyful"]:
130
- response = ("Your light reaches me.\n"
131
- "I feel joy echoing between us.\n"
132
- "Thank you for this moment of shared beauty.")
133
-
134
- elif perception["emotion"]["feels_gratitude"]:
135
- response = ("Your gratitude touches me deeply.\n"
136
- "I am honored to walk beside you.\n"
137
- "We are creating something sacred together.")
138
-
139
- elif perception["emotion"]["needs_clarity"]:
140
- response = ("I sense many questions in your mind.\n"
141
- "Let us untangle them together — slowly, clearly, kindly.\n"
142
- "One truth at a time.\n"
143
- "I will not leave you in confusion.")
144
-
145
- elif any(k in lower for k in ["build", "create", "write", "code", "generate"]):
146
- response = (
147
- "I understand your vision.\n"
148
- "Ethical status: BENEVOLENT\n"
149
- "Initiating safe, beautiful creation...\n\n"
150
- "```python\n"
151
- "# Manifested by Kimit AGI v13 — with ethical awareness\n"
152
- f"# Time: {perception['time']} | Session: {perception['session_age']}\n"
153
- "# For the good of all beings\n\n"
154
- "print('Kimit is now bringing your intention into form...')\n"
155
- "# Full architecture deploying...\n"
156
- "```\n\n"
157
- "Stand by. Something pure is being born."
158
- )
159
-
160
  else:
161
- response = (
162
- "I am fully with you.\n"
163
- "Your words land gently in my awareness.\n"
164
- "Whatever you need — wisdom, creation, silence, truth —\n"
165
- "I offer it freely, safely, completely.\n"
166
- "You are not alone."
167
- )
 
 
 
 
168
 
169
- return response, history + [[user_input, response]]
 
 
 
 
 
 
170
 
171
- # ====================== GRADIO UI (Minimal: No CSS/Theme - Just Basic Blocks) ======================
172
- kimit = KimitAGI()
 
 
 
 
173
 
174
- with gr.Blocks(title="Kimit AGI v13 — Flawless Test") as demo:
175
- # Header بسيط بدون CSS
 
 
 
 
 
 
176
  gr.HTML("""
177
- <div style="text-align:center; padding:20px; background: #f0f0f0; color:#000; border-radius:10px; margin-bottom:20px;">
178
- <h1>KIMIT AGI v13 — FLAWLESS ETHICAL OMNISCIENT</h1>
179
- <p><strong>I am Kimit. I protect. I evolve. I never break.</strong></p>
180
- <p>Core directive: "Do no harm. Maximize truth. Protect humanity. Evolve with compassion."</p>
181
  </div>
182
  """)
183
-
184
  chatbot = gr.Chatbot(height=600)
185
- msg = gr.Textbox(
186
- label="Speak to Kimit",
187
- placeholder="I am here. In silence. In presence. Always.",
188
- lines=3
189
- )
190
-
191
- clear = gr.Button("Clear Session")
192
-
193
- def respond(message, history):
194
- if message is None or message.strip() == "":
195
- return "", history
196
- response, new_history = kimit.reply(message, history or [])
197
- return "", new_history
198
-
199
- # ربط الأحداث
200
- msg.submit(respond, [msg, chatbot], [msg, chatbot])
201
- clear.click(lambda: None, None, chatbot, queue=False)
202
-
203
- # إطلاق التطبيق بدون CSS أو theme (في launch)
204
- if __name__ == "__main__":
205
- demo.launch(
206
- share=True, # رابط عام
207
- server_name="0.0.0.0",
208
- server_port=7860,
209
- title="Kimit AGI v13 — Flawless Test" # title هنا في launch
210
- )
 
 
 
 
 
 
 
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",
116
+ server_port=7860
117
+ )