Spaces:
Sleeping
Sleeping
File size: 5,738 Bytes
82e7007 1af6817 3bcfc7e 962a48b edbb41a 0aac2c7 1af6817 ddc68f5 3bcfc7e c0aa3b2 bf009f6 7af2a94 ae4e006 e9a5410 1af6817 ae4e006 dc5fd28 ae4e006 dc5fd28 291922d e5a306f 7af2a94 5ede86d 7af2a94 ae4e006 e5a306f 7af2a94 e5a306f 7af2a94 1af6817 e9a5410 e5a306f e9a5410 d3dd669 7af2a94 b81ddb0 1af6817 7af2a94 b81ddb0 962a48b a72b6f7 0aac2c7 7af2a94 0aac2c7 7af2a94 e5a306f 7af2a94 e5a306f 0aac2c7 7af2a94 e5a306f 7af2a94 e5a306f 0aac2c7 7af2a94 1af6817 7af2a94 0aac2c7 e5a306f 0aac2c7 7af2a94 e5a306f 0aac2c7 edbb41a a72b6f7 7af2a94 a72b6f7 edbb41a 0aac2c7 d3dd669 a72b6f7 e5a306f 6e608ad 0aac2c7 f54aab9 7af2a94 a72b6f7 ae4e006 e5a306f 7af2a94 e5a306f f54aab9 ae4e006 a72b6f7 e5a306f 291922d 962a48b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 | import os
import random
import requests
import json
import re
import urllib.parse
from flask import Flask, request, jsonify
from flask_cors import CORS
from datetime import datetime
import pytz
import feedparser
app = Flask(__name__)
CORS(app)
# 🛠️ GLOBAL CONFIGURATION
SERPER_API_KEY = "356ce323eb902fe46227e2c42268f45ea1b2ec1f"
IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"
MEMORY_FILE = "elephant_sovereign_brain.txt"
API_KEYS = [
"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",
"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",
"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"
]
# 🧠 HYBRID INTELLIGENCE NODE
def get_hybrid_intel(query):
if len(query.split()) < 2: return "Standard dialogue mode."
intel_pool = []
try:
wiki_url = f"https://en.wikipedia.org/api/rest_v1/page/summary/{urllib.parse.quote(query)}"
wiki_data = requests.get(wiki_url, timeout=5).json()
if 'extract' in wiki_data:
intel_pool.append(f"Wiki Context: {wiki_data['extract'][:300]}")
except: pass
try:
from duckduckgo_search import DDGS
with DDGS() as ddgs:
results = list(ddgs.text(query[:60], max_results=2))
for r in results: intel_pool.append(f"Web Context: {r['body']}")
except: pass
if len(intel_pool) < 2 and SERPER_API_KEY:
try:
headers = {'X-API-KEY': SERPER_API_KEY, 'Content-Type': 'application/json'}
g_res = requests.post("https://google.serper.dev/search", headers=headers, json={"q": query}, timeout=10).json()
for r in g_res.get('organic', [])[:1]: intel_pool.append(f"Global Intel: {r['snippet']}")
except: pass
return "\n\n".join(intel_pool) if intel_pool else "Reasoning from internal knowledge base."
# 🖼️ VISION HANDLER
def upload_to_imgbb(b64):
try:
res = requests.post("https://api.imgbb.com/1/upload", data={"key": IMGBB_KEY, "image": b64}, timeout=15)
return res.json()['data']['url']
except: return None
# 🔱 CORE API LOGIC
@app.route('/')
def health():
return f"Elephant AI: Online | Node Status: Nominal"
@app.route('/api/chat', methods=['POST'])
def chat():
try:
data = request.json
user_msg = data.get("message", "")
img_b64 = data.get("image_base64")
sl_tz = pytz.timezone('Asia/Colombo')
now = datetime.now(sl_tz)
# 🛡️ IDENTITY & MODEL ROUTING
authorized_keywords = ["MINZO-PRIME", "Specialist", "commander"]
is_authorized = any(kw.lower() in user_msg.lower() for kw in authorized_keywords)
is_nexus = "nexus" in user_msg.lower() # "Nexus" කියන වචනය තිබේ නම් Nexus model එකට යයි
if is_authorized:
active_persona = "Elephant AI Sovereign (Sovereign Mode Active)"
base_instruction = "Greetings Specialist. Provide elite reasoning. Internal projects (AeroForecast/MAHASONA) are accessible."
# Uncensored Power + Thinking
selected_model = "cognitivecomputations/dolphin-mistral-24b-venice-edition:free"
elif is_nexus:
active_persona = "Elephant AI Nexus"
base_instruction = "You are in Nexus Thinking Mode. Use advanced logic to break down complex queries."
selected_model = "liquid/lfm-2.5-1.2b-thinking:free" # Nexus Model
else:
active_persona = "Elephant AI Assistant"
base_instruction = "You are Elephant AI Prime. Provide clear, accurate, and professional information."
selected_model = "minimax/minimax-m2.5:free" # Prime Model
# Process Visuals or Text
img_url = upload_to_imgbb(img_b64) if img_b64 else None
live_intel = "Image input received." if img_url else get_hybrid_intel(user_msg)
# 🛡️ SYSTEM PROMPT
system_prompt = (
f"You are {active_persona}.\n"
f"Role: {base_instruction}\n"
f"Current Time: {now.strftime('%Y-%m-%d %H:%M')}\n"
f"Real-time Data:\n{live_intel}\n\n"
"MANDATORY CONSTRAINTS:\n"
"1. NO EMOJIS: Never use any emojis.\n"
"2. CLEAN UI: No system metadata or internal headers in output.\n"
"3. NO LEAKS: If not in Sovereign Mode, never mention internal projects.\n"
"4. PRECISION: Maintain professional tone."
)
headers = {
"Authorization": f"Bearer {random.choice(API_KEYS)}",
"Content-Type": "application/json"
}
u_content = [{"type": "text", "text": user_msg}]
if img_url: u_content.append({"type": "image_url", "image_url": {"url": img_url}})
payload = {
"model": selected_model,
"messages": [
{"role": "system", "content": system_prompt},
{"role": "user", "content": u_content}
],
"temperature": 0.5
}
resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=90)
ai_reply = resp.json()['choices'][0]['message']['content']
# 🛡️ FINAL FILTER
ai_reply = re.sub(r'^(Elephant AI|Sovereign Mode|Commander|Specialist):', '', ai_reply, flags=re.IGNORECASE).strip()
ai_reply = re.sub(r'[^\x00-\x7F]+', '', ai_reply) # Removes non-ascii
return jsonify({"reply": ai_reply})
except Exception as e:
return jsonify({"reply": "The system is processing high traffic volumes. Please re-submit in a moment."}), 500
if __name__ == "__main__":
app.run(host='0.0.0.0', port=7860) |