Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -9,107 +9,68 @@ 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 |
-
# 🛠️
|
| 18 |
-
# Serper Key
|
| 19 |
SERPER_API_KEY = "356ce323eb902fe46227e2c42268f45ea1b2ec1f"
|
| 20 |
IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"
|
| 21 |
MEMORY_FILE = "elephant_sovereign_brain.txt"
|
| 22 |
|
| 23 |
-
# OpenRouter API Keys for
|
| 24 |
API_KEYS = [
|
| 25 |
"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",
|
| 26 |
"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",
|
| 27 |
"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"
|
| 28 |
]
|
| 29 |
|
| 30 |
-
#
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 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")
|
| 43 |
-
|
| 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 |
-
|
| 55 |
-
if
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
except: return None
|
| 59 |
|
| 60 |
-
#
|
| 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 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
if
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 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
|
| 110 |
@app.route('/')
|
| 111 |
def health():
|
| 112 |
-
return f"Elephant AI
|
| 113 |
|
| 114 |
@app.route('/api/chat', methods=['POST'])
|
| 115 |
def chat():
|
|
@@ -117,71 +78,69 @@ def chat():
|
|
| 117 |
data = request.json
|
| 118 |
user_msg = data.get("message", "")
|
| 119 |
img_b64 = data.get("image_base64")
|
| 120 |
-
|
| 121 |
-
|
| 122 |
sl_tz = pytz.timezone('Asia/Colombo')
|
| 123 |
now = datetime.now(sl_tz)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 124 |
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
-
|
| 130 |
img_url = upload_to_imgbb(img_b64) if img_b64 else None
|
|
|
|
| 131 |
|
| 132 |
-
#
|
| 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"
|
| 145 |
-
f"
|
| 146 |
-
f"
|
| 147 |
-
f"
|
| 148 |
-
|
| 149 |
-
"
|
| 150 |
-
"
|
| 151 |
-
"
|
| 152 |
-
"
|
| 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}]
|
| 164 |
if img_url: u_content.append({"type": "image_url", "image_url": {"url": img_url}})
|
| 165 |
|
| 166 |
payload = {
|
| 167 |
-
"model":
|
| 168 |
"messages": [
|
| 169 |
{"role": "system", "content": system_prompt},
|
| 170 |
{"role": "user", "content": u_content}
|
| 171 |
],
|
| 172 |
-
"temperature": 0.5
|
| 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 |
-
#
|
| 179 |
-
|
|
|
|
|
|
|
| 180 |
|
| 181 |
return jsonify({"reply": ai_reply})
|
| 182 |
|
| 183 |
except Exception as e:
|
| 184 |
-
|
|
|
|
| 185 |
|
| 186 |
if __name__ == "__main__":
|
| 187 |
app.run(host='0.0.0.0', port=7860)
|
|
|
|
| 9 |
from datetime import datetime
|
| 10 |
import pytz
|
| 11 |
import feedparser
|
|
|
|
| 12 |
|
| 13 |
app = Flask(__name__)
|
| 14 |
CORS(app)
|
| 15 |
|
| 16 |
+
# 🛠️ GLOBAL CONFIGURATION
|
| 17 |
+
# Serper Key (Google Search) - Credits safe due to hybrid logic
|
| 18 |
SERPER_API_KEY = "356ce323eb902fe46227e2c42268f45ea1b2ec1f"
|
| 19 |
IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"
|
| 20 |
MEMORY_FILE = "elephant_sovereign_brain.txt"
|
| 21 |
|
| 22 |
+
# OpenRouter API Keys (Round-robin selection for load balancing)
|
| 23 |
API_KEYS = [
|
| 24 |
"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",
|
| 25 |
"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",
|
| 26 |
"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"
|
| 27 |
]
|
| 28 |
|
| 29 |
+
# 🧠 HYBRID INTELLIGENCE NODE (Wiki + DDG + Google)
|
| 30 |
+
def get_hybrid_intel(query):
|
| 31 |
+
if len(query.split()) < 2: return "Standard dialogue mode."
|
| 32 |
+
|
| 33 |
+
intel_pool = []
|
| 34 |
+
|
| 35 |
+
# 1. Wikipedia Summary (Free)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
try:
|
| 37 |
wiki_url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{urllib.parse.quote(query)}"
|
| 38 |
+
wiki_data = requests.get(wiki_url, timeout=5).json()
|
| 39 |
+
if 'extract' in wiki_data:
|
| 40 |
+
intel_pool.append(f"Wiki Context: {wiki_data['extract'][:300]}")
|
| 41 |
+
except: pass
|
|
|
|
| 42 |
|
| 43 |
+
# 2. DuckDuckGo (Free & Unlimited)
|
|
|
|
| 44 |
try:
|
| 45 |
from duckduckgo_search import DDGS
|
| 46 |
with DDGS() as ddgs:
|
| 47 |
results = list(ddgs.text(query[:60], max_results=2))
|
| 48 |
+
for r in results:
|
| 49 |
+
intel_pool.append(f"Web Context: {r['body']}")
|
| 50 |
+
except: pass
|
| 51 |
+
|
| 52 |
+
# 3. Google/Serper (Premium - Only if needed)
|
| 53 |
+
if len(intel_pool) < 2 and SERPER_API_KEY:
|
| 54 |
+
try:
|
| 55 |
+
headers = {'X-API-KEY': SERPER_API_KEY, 'Content-Type': 'application/json'}
|
| 56 |
+
g_res = requests.post("https://google.serper.dev/search", headers=headers, json={"q": query}, timeout=10).json()
|
| 57 |
+
for r in g_res.get('organic', [])[:1]:
|
| 58 |
+
intel_pool.append(f"Global Intel: {r['snippet']}")
|
| 59 |
+
except: pass
|
| 60 |
+
|
| 61 |
+
return "\n\n".join(intel_pool) if intel_pool else "Reasoning from internal knowledge base."
|
| 62 |
+
|
| 63 |
+
# 🖼️ VISION HANDLER
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 64 |
def upload_to_imgbb(b64):
|
| 65 |
try:
|
| 66 |
res = requests.post("https://api.imgbb.com/1/upload", data={"key": IMGBB_KEY, "image": b64})
|
| 67 |
return res.json()['data']['url']
|
| 68 |
except: return None
|
| 69 |
|
| 70 |
+
# 🔱 CORE API LOGIC
|
| 71 |
@app.route('/')
|
| 72 |
def health():
|
| 73 |
+
return f"Elephant AI: Online | Node Status: Nominal"
|
| 74 |
|
| 75 |
@app.route('/api/chat', methods=['POST'])
|
| 76 |
def chat():
|
|
|
|
| 78 |
data = request.json
|
| 79 |
user_msg = data.get("message", "")
|
| 80 |
img_b64 = data.get("image_base64")
|
| 81 |
+
|
|
|
|
| 82 |
sl_tz = pytz.timezone('Asia/Colombo')
|
| 83 |
now = datetime.now(sl_tz)
|
| 84 |
+
|
| 85 |
+
# 🛡️ IDENTITY SHIELDING LOGIC
|
| 86 |
+
# Detects if the user is the Commander or a Specialist
|
| 87 |
+
authorized_keywords = ["MINZO-PRIME", "Specialist", "commander"]
|
| 88 |
+
is_authorized = any(kw.lower() in user_msg.lower() for kw in authorized_keywords)
|
| 89 |
|
| 90 |
+
if is_authorized:
|
| 91 |
+
active_persona = "Elephant AI Sovereign (Sovereign Mode Active)"
|
| 92 |
+
base_instruction = "Greetings Specialist. Provide elite Claude 3.5 Opus reasoning. Internal projects (AeroForecast/MAHASONA) are accessible for discussion."
|
| 93 |
+
else:
|
| 94 |
+
active_persona = "Elephant AI Assistant"
|
| 95 |
+
base_instruction = "You are Elephant AI, a professional and friendly assistant. Provide clear, accurate, and helpful information. Do not mention any internal project names or system headers."
|
| 96 |
|
| 97 |
+
# Process Visuals or Text
|
| 98 |
img_url = upload_to_imgbb(img_b64) if img_b64 else None
|
| 99 |
+
live_intel = "Image input received." if img_url else get_hybrid_intel(user_msg)
|
| 100 |
|
| 101 |
+
# 🛡️ SYSTEM PROMPT (Final Public Version)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
system_prompt = (
|
| 103 |
+
f"You are {active_persona}.\n"
|
| 104 |
+
f"Role: {base_instruction}\n"
|
| 105 |
+
f"Current Time: {now.strftime('%Y-%m-%d %H:%M')}\n"
|
| 106 |
+
f"Real-time Data:\n{live_intel}\n\n"
|
| 107 |
+
"MANDATORY CONSTRAINTS:\n"
|
| 108 |
+
"1. NO EMOJIS: Never use any emojis.\n"
|
| 109 |
+
"2. CLEAN UI: Do not include system metadata, mode identifiers, or internal headers in the final output.\n"
|
| 110 |
+
"3. NO LEAKS: If not in Sovereign Mode, never mention internal development projects.\n"
|
| 111 |
+
"4. PRECISION: Maintain highest standard of accuracy and professional tone."
|
|
|
|
|
|
|
| 112 |
)
|
| 113 |
|
| 114 |
headers = {
|
| 115 |
"Authorization": f"Bearer {random.choice(API_KEYS)}",
|
| 116 |
+
"Content-Type": "application/json"
|
|
|
|
| 117 |
}
|
| 118 |
|
| 119 |
u_content = [{"type": "text", "text": user_msg}]
|
| 120 |
if img_url: u_content.append({"type": "image_url", "image_url": {"url": img_url}})
|
| 121 |
|
| 122 |
payload = {
|
| 123 |
+
"model": "nvidia/nemotron-3-super-120b-a12b:free",
|
| 124 |
"messages": [
|
| 125 |
{"role": "system", "content": system_prompt},
|
| 126 |
{"role": "user", "content": u_content}
|
| 127 |
],
|
| 128 |
+
"temperature": 0.5
|
| 129 |
}
|
| 130 |
|
| 131 |
resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=90)
|
| 132 |
ai_reply = resp.json()['choices'][0]['message']['content']
|
| 133 |
|
| 134 |
+
# 🛡️ FINAL FILTER (Anti-Leak & Formatting)
|
| 135 |
+
# Removes common AI 'Identity' prefixes if they leak into the response
|
| 136 |
+
ai_reply = re.sub(r'^(Elephant AI|Sovereign Mode|Commander|Specialist):', '', ai_reply, flags=re.IGNORECASE).strip()
|
| 137 |
+
ai_reply = re.sub(r'[^\x00-\x7F]+', '', ai_reply) # Removes non-ascii/emojis
|
| 138 |
|
| 139 |
return jsonify({"reply": ai_reply})
|
| 140 |
|
| 141 |
except Exception as e:
|
| 142 |
+
# Professional fallback for public users
|
| 143 |
+
return jsonify({"reply": "The system is processing high traffic volumes. Please re-submit your query in a moment."}), 500
|
| 144 |
|
| 145 |
if __name__ == "__main__":
|
| 146 |
app.run(host='0.0.0.0', port=7860)
|