Spaces:
Sleeping
Sleeping
Update app.py
Browse files
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 = "
|
| 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 |
-
#
|
| 24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
with open(MEMORY_FILE, "a", encoding="utf-8") as f:
|
| 26 |
-
f.write(f"|
|
| 27 |
|
| 28 |
-
def
|
| 29 |
if os.path.exists(MEMORY_FILE):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
try:
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
#
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 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
|
| 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 |
-
# 🔱
|
| 60 |
@app.route('/')
|
| 61 |
-
def
|
| 62 |
-
return f"🐘 Elephant AI Core: ONLINE |
|
| 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
|
| 77 |
-
if
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
else:
|
| 81 |
|
| 82 |
-
current_memory =
|
| 83 |
-
img_url =
|
| 84 |
|
| 85 |
-
# 🔱
|
| 86 |
if img_url:
|
| 87 |
selected_model = "google/gemma-4-31b-it:free"
|
| 88 |
-
active_tier = "VISION-
|
| 89 |
-
|
| 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"
|
| 103 |
-
f"
|
| 104 |
-
f"
|
| 105 |
-
f"
|
| 106 |
-
f"
|
| 107 |
-
"INSTRUCTION: Use
|
| 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.
|
| 127 |
}
|
| 128 |
|
| 129 |
-
resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=
|
| 130 |
resp_data = resp.json()
|
| 131 |
|
| 132 |
if 'choices' in resp_data:
|
| 133 |
ai_reply = resp_data['choices'][0]['message']['content']
|
| 134 |
-
|
| 135 |
-
return jsonify({"reply": status_tag + ai_reply})
|
| 136 |
else:
|
| 137 |
-
return jsonify({"reply": f"
|
| 138 |
|
| 139 |
except Exception as e:
|
| 140 |
-
return jsonify({"reply": f"
|
| 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)
|