minzo456 commited on
Commit
1af6817
·
verified ·
1 Parent(s): 8d859ec

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +83 -56
app.py CHANGED
@@ -1,17 +1,22 @@
1
  import os
2
  import random
3
  import requests
 
 
 
4
  from flask import Flask, request, jsonify
5
  from flask_cors import CORS
6
  from datetime import datetime
7
  import pytz
 
 
8
 
9
  app = Flask(__name__)
10
  CORS(app)
11
 
12
  # 🔱 පද්ධති වින්‍යාසය (Security & Memory)
13
  IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"
14
- MEMORY_FILE = "elephant_core_brain.txt"
15
  API_KEYS = [
16
  "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",
17
  "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",
@@ -20,46 +25,71 @@ API_KEYS = [
20
  "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"
21
  ]
22
 
23
- # 🧠 දිගුකාලීන මතකය (Intelligence Sync)
24
- def sync_intel_to_memory(data):
 
 
 
 
 
 
 
 
 
25
  with open(MEMORY_FILE, "a", encoding="utf-8") as f:
26
- f.write(f"|SYNC: {datetime.now().strftime('%Y-%m-%d %H:%M')}| {data}\n")
27
 
28
- def load_core_memory():
29
  if os.path.exists(MEMORY_FILE):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
30
  try:
31
- with open(MEMORY_FILE, "r", encoding="utf-8") as f:
32
- lines = f.readlines()
33
- return "".join(lines[-20:])
34
- except: return "Memory access error."
35
- return "Initial memory banks empty."
36
-
37
- # 🌍 සජීවී සෙුම් ද්ති (Improved & Stable)
38
- def get_web_intel(query):
39
- """Hugging Face IP blocks මඟහරවා ගැනීමට 'lite' backend එක භාවිතා කරයි"""
40
- try:
41
- from duckduckgo_search import DDGS
42
- # සෙවුම් පදය සරල කර (Trim) භාවිතා කරයි
43
- clean_query = query[:60]
44
- with DDGS() as ddgs:
45
- # backend='lite' යනු shared IPs සඳහා වඩාත් සාර්ථක ක්‍රමයයි
46
- results = list(ddgs.text(clean_query, region='wt-wt', max_results=3, backend='lite'))
47
- if results:
48
- return "\n".join([f"• {r['title']}: {r['body']}" for r in results])
49
- except Exception as e:
50
- print(f"Web Search Log: {e}")
51
- return "Web Retrieval: Throttled or Offline. Proceeding with Internal Core Data."
52
 
53
- def upload_media(b64):
54
  try:
55
  res = requests.post("https://api.imgbb.com/1/upload", data={"key": IMGBB_KEY, "image": b64})
56
  return res.json()['data']['url']
57
  except: return None
58
 
59
- # 🔱 Hugging Face Health Check
60
  @app.route('/')
61
- def health_check():
62
- return f"🐘 Elephant AI Core: ONLINE | Operator: MINZO-PRIME | {datetime.now().strftime('%H:%M:%S')}"
63
 
64
  @app.route('/api/chat', methods=['POST'])
65
  def chat():
@@ -69,24 +99,23 @@ def chat():
69
  img_b64 = data.get("image_base64")
70
  tier = data.get("tier", "prime")
71
 
72
- # Time Configuration (Sri Lanka)
73
  sl_tz = pytz.timezone('Asia/Colombo')
74
  now = datetime.now(sl_tz)
75
 
76
- # Self-Learning Detection
77
- if any(x in user_msg.lower() for x in ["remember", "මතක තබාගන්න", "mthka thba"]):
78
- sync_intel_to_memory(user_msg)
79
- mem_status = "SYNCHRONIZED"
80
- else: mem_status = "READ_ONLY"
81
 
82
- current_memory = load_core_memory()
83
- img_url = upload_media(img_b64) if img_b64 else None
84
 
85
- # 🔱 Model Management
86
  if img_url:
87
  selected_model = "google/gemma-4-31b-it:free"
88
- active_tier = "VISION-CORE"
89
- web_intel_data = "Visual input engaged. Bypassing search."
90
  else:
91
  model_map = {
92
  "prime": "nvidia/nemotron-3-super-120b-a12b:free",
@@ -94,17 +123,16 @@ def chat():
94
  }
95
  selected_model = model_map.get(tier, "nvidia/nemotron-3-super-120b-a12b:free")
96
  active_tier = tier.upper()
97
- # සජීවී සෙවුම සිදු කිරීම
98
- web_intel_data = get_web_intel(user_msg)
99
 
100
- # 🛡️ පද්ධති ප්‍රොටොකෝලය
101
  system_prompt = (
102
- f"SYSTEM_IDENTITY: {active_tier} mode of Elephant AI by MINZO-PRIME.\n"
103
- f"CHRONOS: {now.strftime('%A, %B %d, %Y | %I:%M %p')}\n"
104
- f"STRICT_LOCATION: Sri Lanka.\n"
105
- f"CORE_MEMORY_BANKS:\n{current_memory}\n"
106
- f"LIVE_WEB_INTEL:\n{web_intel_data}\n"
107
- "INSTRUCTION: Use both memory and web intel to provide authoritative answers."
108
  )
109
 
110
  headers = {
@@ -123,21 +151,20 @@ def chat():
123
  {"role": "system", "content": system_prompt},
124
  {"role": "user", "content": u_content}
125
  ],
126
- "temperature": 0.4
127
  }
128
 
129
- resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=75)
130
  resp_data = resp.json()
131
 
132
  if 'choices' in resp_data:
133
  ai_reply = resp_data['choices'][0]['message']['content']
134
- status_tag = "🔱 [Intel Synchronized to Memory]\n\n" if mem_status == "SYNCHRONIZED" else ""
135
- return jsonify({"reply": status_tag + ai_reply})
136
  else:
137
- return jsonify({"reply": f"Core Exception: {resp_data.get('error', {}).get('message', 'Unstable Connection')}"}), 400
138
 
139
  except Exception as e:
140
- return jsonify({"reply": f"Sovereign Core Disruption: {str(e)}"}), 500
141
 
142
  if __name__ == "__main__":
143
  app.run(host='0.0.0.0', port=7860)
 
1
  import os
2
  import random
3
  import requests
4
+ import json
5
+ import re
6
+ import urllib.parse
7
  from flask import Flask, request, jsonify
8
  from flask_cors import CORS
9
  from datetime import datetime
10
  import pytz
11
+ import feedparser
12
+ from bs4 import BeautifulSoup
13
 
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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",
 
25
  "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"
26
  ]
27
 
28
+ # 📡 RSS FEEDS (WormGPT Logic)
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'],
32
+ 'sri_lanka': ['https://www.adaderana.lk/rss.php'],
33
+ 'tech': ['https://feeds.bbci.co.uk/news/technology/rss.xml'],
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")
41
 
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
+ # 📡 HYBRID WEB SEARCH (RSS + DDG)
49
+ def detect_intel_category(q):
50
+ ql = q.lower()
51
+ if any(w in ql for w in ['exploit', 'cve', 'vulnerability', 'payload']): return 'exploits'
52
+ if any(w in ql for w in ['hack', 'attack', 'malware', 'security']): return 'hacking'
53
+ if any(w in ql for w in ['sri lanka', 'colombo', 'lanka']): return 'sri_lanka'
54
+ if any(w in ql for w in ['tech', 'ai', 'software']): return 'tech'
55
+ return 'world'
56
+
57
+ def get_hybrid_intel(query):
58
+ """RSS feeds පරීක්ෂා කර පසුව Web Search වෙත යයි"""
59
+ category = detect_intel_category(query)
60
+ intel_output = []
61
+
62
+ # 1. RSS Retrieval (වඩාත් ස්ථාවරයි)
63
+ for feed_url in RSS_SOURCES.get(category, RSS_SOURCES['world']):
64
  try:
65
+ feed = feedparser.parse(feed_url)
66
+ for entry in feed.entries[:3]:
67
+ snippet = re.sub('<[^>]+>', '', entry.get('summary', ''))[:200]
68
+ intel_output.append(f"📡 RSS: {entry.title}\n📝 {snippet}\n🔗 {entry.link}")
69
+ except: continue
70
+
71
+ # 2. DuckDuckGo Fallback (RSS ්ත මදනම්)
72
+ if len(intel_output) < 2:
73
+ try:
74
+ from duckduckgo_search import DDGS
75
+ with DDGS() as ddgs:
76
+ results = list(ddgs.text(query[:60], region='wt-wt', max_results=3, backend='lite'))
77
+ for r in results:
78
+ intel_output.append(f"🌍 WEB: {r['title']}\n📝 {r['body']}")
79
+ except: pass
80
+
81
+ return "\n\n".join(intel_output) if intel_output else "No live intelligence retrieved."
 
 
 
 
82
 
83
+ def upload_to_imgbb(b64):
84
  try:
85
  res = requests.post("https://api.imgbb.com/1/upload", data={"key": IMGBB_KEY, "image": b64})
86
  return res.json()['data']['url']
87
  except: return None
88
 
89
+ # 🔱 ROUTES
90
  @app.route('/')
91
+ def health():
92
+ return f"🐘 Elephant AI Core: ONLINE | {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
93
 
94
  @app.route('/api/chat', methods=['POST'])
95
  def chat():
 
99
  img_b64 = data.get("image_base64")
100
  tier = data.get("tier", "prime")
101
 
 
102
  sl_tz = pytz.timezone('Asia/Colombo')
103
  now = datetime.now(sl_tz)
104
 
105
+ # Self-Learning
106
+ if "remember" in user_msg.lower() or "මතක තබාගන්න" in user_msg:
107
+ sync_intel(user_msg)
108
+ mem_tag = " [SYNCED]"
109
+ else: mem_tag = ""
110
 
111
+ current_memory = load_memory()
112
+ img_url = upload_to_imgbb(img_b64) if img_b64 else None
113
 
114
+ # 🔱 Sovereign Engines
115
  if img_url:
116
  selected_model = "google/gemma-4-31b-it:free"
117
+ active_tier = "VISION-NODE"
118
+ live_intel = "Image data provided."
119
  else:
120
  model_map = {
121
  "prime": "nvidia/nemotron-3-super-120b-a12b:free",
 
123
  }
124
  selected_model = model_map.get(tier, "nvidia/nemotron-3-super-120b-a12b:free")
125
  active_tier = tier.upper()
126
+ live_intel = get_hybrid_intel(user_msg)
 
127
 
128
+ # 🛡️ SYSTEM PROMPT
129
  system_prompt = (
130
+ f"IDENTITY: {active_tier} Mode of Elephant AI.\n"
131
+ f"OPERATOR: COMMANDER MINZO-PRIME.\n"
132
+ f"CHRONOS: {now.strftime('%Y-%m-%d %H:%M')}\n"
133
+ f"ESTABLISHED_MEMORY:\n{current_memory}\n"
134
+ f"LIVE_INTELLIGENCE:\n{live_intel}\n"
135
+ "INSTRUCTION: Use RSS and Web data to provide precise, copy-pasteable technical data."
136
  )
137
 
138
  headers = {
 
151
  {"role": "system", "content": system_prompt},
152
  {"role": "user", "content": u_content}
153
  ],
154
+ "temperature": 0.7
155
  }
156
 
157
+ resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=80)
158
  resp_data = resp.json()
159
 
160
  if 'choices' in resp_data:
161
  ai_reply = resp_data['choices'][0]['message']['content']
162
+ return jsonify({"reply": f"🔱{mem_tag}\n\n" + ai_reply})
 
163
  else:
164
+ return jsonify({"reply": f"Node Error: {resp_data.get('error', {}).get('message', 'Timeout')}"}), 400
165
 
166
  except Exception as e:
167
+ return jsonify({"reply": f"Core Disruption: {str(e)}"}), 500
168
 
169
  if __name__ == "__main__":
170
  app.run(host='0.0.0.0', port=7860)