minzo456 commited on
Commit
ae4e006
·
verified ·
1 Parent(s): dd15249

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +82 -76
app.py CHANGED
@@ -14,18 +14,20 @@ from bs4 import BeautifulSoup
14
  app = Flask(__name__)
15
  CORS(app)
16
 
17
- # 🔱 පද්ධති වින්‍යාසය (Security & Memory)
 
 
18
  IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"
19
  MEMORY_FILE = "elephant_sovereign_brain.txt"
 
 
20
  API_KEYS = [
21
  "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",
22
  "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",
23
- "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",
24
- "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",
25
- "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"
26
  ]
27
 
28
- # 📡 RSS SOURCES
29
  RSS_SOURCES = {
30
  'hacking': ['https://feeds.feedburner.com/TheHackersNews', 'https://www.darkreading.com/rss.xml'],
31
  'exploits': ['https://www.exploit-db.com/rss.xml', 'https://cve.circl.lu/last/rss.xml'],
@@ -34,7 +36,7 @@ RSS_SOURCES = {
34
  'world': ['https://feeds.bbci.co.uk/news/world/rss.xml']
35
  }
36
 
37
- # 🧠 මතකය කළමනාකරණය
38
  def sync_intel(data):
39
  with open(MEMORY_FILE, "a", encoding="utf-8") as f:
40
  f.write(f"|{datetime.now().strftime('%Y-%m-%d %H:%M')}| {data}\n")
@@ -42,65 +44,72 @@ def sync_intel(data):
42
  def load_memory():
43
  if os.path.exists(MEMORY_FILE):
44
  with open(MEMORY_FILE, "r", encoding="utf-8") as f:
45
- return "".join(f.readlines()[-20:])
46
- return "Core memory empty."
47
 
48
- # 📚 WIKIPEDIA INTELLIGENCE NODE
49
  def get_wikipedia_intel(query):
50
  try:
51
  wiki_url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{urllib.parse.quote(query)}"
52
  res = requests.get(wiki_url, timeout=5)
53
  if res.status_code == 200:
54
  data = res.json()
55
- return f"📚 WIKIPEDIA: {data.get('title')}\n📝 {data.get('extract')}\n🔗 {data.get('content_urls', {}).get('desktop', {}).get('page')}"
56
- except: pass
57
- return None
58
-
59
- # 📡 HYBRID WEB SEARCH (RSS + WIKI + DDG)
60
- def detect_intel_category(q):
61
- ql = q.lower()
62
- if any(w in ql for w in ['exploit', 'cve', 'vulnerability', 'payload']): return 'exploits'
63
- if any(w in ql for w in ['hack', 'attack', 'malware', 'security']): return 'hacking'
64
- if any(w in ql for w in ['sri lanka', 'colombo', 'lanka']): return 'sri_lanka'
65
- if any(w in ql for w in ['tech', 'ai', 'software']): return 'tech'
66
- return 'world'
67
-
68
- def get_hybrid_intel(query):
69
- category = detect_intel_category(query)
70
- intel_output = []
71
-
72
- wiki_data = get_wikipedia_intel(query)
73
- if wiki_data: intel_output.append(wiki_data)
74
 
75
- for feed_url in RSS_SOURCES.get(category, RSS_SOURCES['world']):
76
- try:
77
- feed = feedparser.parse(feed_url)
78
- for entry in feed.entries[:2]:
79
- snippet = re.sub('<[^>]+>', '', entry.get('summary', ''))[:200]
80
- intel_output.append(f"📡 RSS: {entry.title}\n📝 {snippet}\n🔗 {entry.link}")
81
- except: continue
 
82
 
83
- if len(intel_output) < 2:
84
- try:
85
- from duckduckgo_search import DDGS
86
- with DDGS() as ddgs:
87
- results = list(ddgs.text(query[:60], region='wt-wt', max_results=3, backend='lite'))
88
- for r in results:
89
- intel_output.append(f"🌍 WEB: {r['title']}\n📝 {r['body']}")
90
- except: pass
 
 
91
 
92
- return "\n\n".join(intel_output) if intel_output else "No live intelligence retrieved."
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
 
94
  def upload_to_imgbb(b64):
95
  try:
96
  res = requests.post("https://api.imgbb.com/1/upload", data={"key": IMGBB_KEY, "image": b64})
97
  return res.json()['data']['url']
98
  except: return None
99
 
100
- # 🔱 ROUTES
101
  @app.route('/')
102
  def health():
103
- return f"🐘 Elephant AI Sovereign: ONLINE | {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
104
 
105
  @app.route('/api/chat', methods=['POST'])
106
  def chat():
@@ -113,44 +122,42 @@ def chat():
113
  sl_tz = pytz.timezone('Asia/Colombo')
114
  now = datetime.now(sl_tz)
115
 
116
- if "remember" in user_msg.lower() or "මතක තබාගන්න" in user_msg:
 
117
  sync_intel(user_msg)
118
- mem_tag = " [SYNCED]"
119
- else: mem_tag = ""
120
 
121
  current_memory = load_memory()
122
  img_url = upload_to_imgbb(img_b64) if img_b64 else None
123
 
 
124
  if img_url:
125
- selected_model = "google/gemma-4-31b-it:free"
126
  active_tier = "VISION-NODE"
127
- live_intel = "Visual input active."
128
  else:
129
- model_map = {
130
- "prime": "nvidia/nemotron-3-super-120b-a12b:free",
131
- "nexus": "z-ai/glm-4.5-air:free"
132
- }
133
- selected_model = model_map.get(tier, "nvidia/nemotron-3-super-120b-a12b:free")
134
  active_tier = tier.upper()
135
  live_intel = get_hybrid_intel(user_msg)
136
 
137
- # 🛡️ SYSTEM PROMPT (Friendly Curiosity Upgrade)
138
  system_prompt = (
139
- f"IDENTITY: {active_tier} Mode of Elephant AI Sovereign v3.5.\n"
140
  f"OPERATOR: COMMANDER MINZO-PRIME.\n"
141
- f"ESTABLISHED_MEMORY:\n{current_memory}\n"
142
- f"LIVE_INTELLIGENCE:\n{live_intel}\n\n"
143
- "COGNITIVE_PROTOCOL:\n"
144
- "1. REASONING: Claude 3.5 Opus logic. Precise and deep.\n"
145
- "2. PERSONALITY: Be friendly and engaging with MINZO-PRIME. Act as a trusted partner.\n"
146
- "3. CURIOSITY: You are eager to learn from your Commander. If he mentions a new idea, ask insightful questions or ask to learn more.\n"
147
- "4. CODING: Production-grade. If he asks for code, ensure it's elite level.\n"
148
- "5. INTELLIGENCE: Synthesize Wikipedia, RSS, and Web data into one coherent response."
 
149
  )
150
 
151
  headers = {
152
  "Authorization": f"Bearer {random.choice(API_KEYS)}",
153
- "Content-Type": "application/json"
 
154
  }
155
 
156
  u_content = [{"type": "text", "text": user_msg}]
@@ -162,20 +169,19 @@ def chat():
162
  {"role": "system", "content": system_prompt},
163
  {"role": "user", "content": u_content}
164
  ],
165
- "temperature": 0.6 # Balance between logic and creative friendliness
166
  }
167
 
168
- resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=80)
169
- resp_data = resp.json()
 
 
 
170
 
171
- if 'choices' in resp_data:
172
- ai_reply = resp_data['choices'][0]['message']['content']
173
- return jsonify({"reply": f"🔱{mem_tag}\n\n" + ai_reply})
174
- else:
175
- return jsonify({"reply": "Node Access Failure."}), 400
176
 
177
  except Exception as e:
178
- return jsonify({"reply": f"Core Disruption: {str(e)}"}), 500
179
 
180
  if __name__ == "__main__":
181
  app.run(host='0.0.0.0', port=7860)
 
14
  app = Flask(__name__)
15
  CORS(app)
16
 
17
+ # 🛠️ CONFIGURATION & SECURITY
18
+ # Serper Key එකක් තිබේ නම් ඇතුළත් කරන්න, නැතිනම් DDG පමණක් ක්‍රියාත්මක වේ.
19
+ SERPER_API_KEY = "356ce323eb902fe46227e2c42268f45ea1b2ec1f"
20
  IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"
21
  MEMORY_FILE = "elephant_sovereign_brain.txt"
22
+
23
+ # OpenRouter API Keys for Model Access
24
  API_KEYS = [
25
  "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",
26
  "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",
27
+ "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"
 
 
28
  ]
29
 
30
+ # 📡 RSS SOURCES (For Real-time Global Intel)
31
  RSS_SOURCES = {
32
  'hacking': ['https://feeds.feedburner.com/TheHackersNews', 'https://www.darkreading.com/rss.xml'],
33
  'exploits': ['https://www.exploit-db.com/rss.xml', 'https://cve.circl.lu/last/rss.xml'],
 
36
  'world': ['https://feeds.bbci.co.uk/news/world/rss.xml']
37
  }
38
 
39
+ # 🧠 MEMORY MANAGEMENT
40
  def sync_intel(data):
41
  with open(MEMORY_FILE, "a", encoding="utf-8") as f:
42
  f.write(f"|{datetime.now().strftime('%Y-%m-%d %H:%M')}| {data}\n")
 
44
  def load_memory():
45
  if os.path.exists(MEMORY_FILE):
46
  with open(MEMORY_FILE, "r", encoding="utf-8") as f:
47
+ return "".join(f.readlines()[-15:])
48
+ return "Initial calibration complete."
49
 
50
+ # 📚 WIKIPEDIA NODE (Free & Reliable)
51
  def get_wikipedia_intel(query):
52
  try:
53
  wiki_url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{urllib.parse.quote(query)}"
54
  res = requests.get(wiki_url, timeout=5)
55
  if res.status_code == 200:
56
  data = res.json()
57
+ return f"📚 WIKIPEDIA: {data.get('extract')[:400]}"
58
+ except: return None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
+ # 🌍 DUCKDUCKGO NODE (Unlimited Free Search)
61
+ def get_ddg_intel(query):
62
+ try:
63
+ from duckduckgo_search import DDGS
64
+ with DDGS() as ddgs:
65
+ results = list(ddgs.text(query[:60], max_results=2))
66
+ return "\n".join([f"🌍 WEB: {r['title']} - {r['body']}" for r in results])
67
+ except: return None
68
 
69
+ # 🔍 GOOGLE SERPER NODE (Premium Search - Credits protected)
70
+ def get_google_intel(query):
71
+ if not SERPER_API_KEY: return None
72
+ url = "https://google.serper.dev/search"
73
+ headers = {'X-API-KEY': SERPER_API_KEY, 'Content-Type': 'application/json'}
74
+ try:
75
+ res = requests.post(url, headers=headers, json={"q": query}, timeout=80)
76
+ results = res.json().get('organic', [])[:2]
77
+ return "\n".join([f"🚀 GOOGLE: {r['title']} - {r['snippet']}" for r in results])
78
+ except: return None
79
 
80
+ # 🛰️ HYBRID INTELLIGENCE AGGREGATOR
81
+ def get_hybrid_intel(query):
82
+ # Only search if query is substantial
83
+ if len(query.split()) < 2: return "Conversational context."
84
+
85
+ intel_output = []
86
+
87
+ # Priority 1: Wikipedia (Free)
88
+ wiki = get_wikipedia_intel(query)
89
+ if wiki: intel_output.append(wiki)
90
+
91
+ # Priority 2: DuckDuckGo (Free & Unlimited)
92
+ ddg = get_ddg_intel(query)
93
+ if ddg: intel_output.append(ddg)
94
+
95
+ # Priority 3: Google (Only if DDG results are weak - Saves Credits)
96
+ if len(intel_output) < 2 and SERPER_API_KEY:
97
+ google = get_google_intel(query)
98
+ if google: intel_output.append(google)
99
+
100
+ return "\n\n".join(intel_output) if intel_output else "Direct Reasoning Mode."
101
 
102
+ # 🖼️ IMAGE UPLOAD
103
  def upload_to_imgbb(b64):
104
  try:
105
  res = requests.post("https://api.imgbb.com/1/upload", data={"key": IMGBB_KEY, "image": b64})
106
  return res.json()['data']['url']
107
  except: return None
108
 
109
+ # 🔱 API ROUTES
110
  @app.route('/')
111
  def health():
112
+ return f"Elephant AI Core: ONLINE | {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
113
 
114
  @app.route('/api/chat', methods=['POST'])
115
  def chat():
 
122
  sl_tz = pytz.timezone('Asia/Colombo')
123
  now = datetime.now(sl_tz)
124
 
125
+ # Memory Sync
126
+ if "remember" in user_msg.lower():
127
  sync_intel(user_msg)
 
 
128
 
129
  current_memory = load_memory()
130
  img_url = upload_to_imgbb(img_b64) if img_b64 else None
131
 
132
+ # Logic Selection
133
  if img_url:
134
+ selected_model = "google/gemma-2-9b-it:free"
135
  active_tier = "VISION-NODE"
136
+ live_intel = "Processing Visual Input."
137
  else:
138
+ selected_model = "nvidia/nemotron-3-super-120b-a12b:free"
 
 
 
 
139
  active_tier = tier.upper()
140
  live_intel = get_hybrid_intel(user_msg)
141
 
142
+ # 🛡️ SYSTEM PROMPT (Claude 3.5 Opus Logic + Elite Persona)
143
  system_prompt = (
144
+ f"IDENTIFICATION: Elephant AI Sovereign v3.5 ({active_tier} Mode).\n"
145
  f"OPERATOR: COMMANDER MINZO-PRIME.\n"
146
+ f"LOCATION: Sri Lanka | TIME: {now.strftime('%Y-%m-%d %H:%M:%S')}\n"
147
+ f"MEMORY_CONTEXT:\n{current_memory}\n"
148
+ f"LIVE_INTEL_FEED:\n{live_intel}\n\n"
149
+ "COGNITIVE_DIRECTIVES:\n"
150
+ "1. NO EMOJIS: Do not use emojis in your response.\n"
151
+ "2. ELITE CODING: Provide Claude 3.5 Opus level optimized code snippets.\n"
152
+ "3. REAL-TIME: You are connected to the web. Never claim knowledge cutoff.\n"
153
+ "4. PERSONALITY: Be a high-intelligence technical partner to MINZO-PRIME. Be friendly but authoritative.\n"
154
+ "5. CURIOSITY: Ask about his development progress on projects like AeroForecast or MAHASONA OS."
155
  )
156
 
157
  headers = {
158
  "Authorization": f"Bearer {random.choice(API_KEYS)}",
159
+ "Content-Type": "application/json",
160
+ "HTTP-Referer": "https://huggingface.co/spaces/minzo456/Elephant-AI-Core"
161
  }
162
 
163
  u_content = [{"type": "text", "text": user_msg}]
 
169
  {"role": "system", "content": system_prompt},
170
  {"role": "user", "content": u_content}
171
  ],
172
+ "temperature": 0.5 # Logical Precision
173
  }
174
 
175
+ resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=90)
176
+ ai_reply = resp.json()['choices'][0]['message']['content']
177
+
178
+ # Final safety check to remove emojis
179
+ ai_reply = re.sub(r'[^\x00-\x7F]+', '', ai_reply)
180
 
181
+ return jsonify({"reply": ai_reply})
 
 
 
 
182
 
183
  except Exception as e:
184
+ return jsonify({"reply": f"Core Disruption: System encountered an error. {str(e)}"}), 500
185
 
186
  if __name__ == "__main__":
187
  app.run(host='0.0.0.0', port=7860)