minzo456's picture
Update app.py
e5a306f verified
Raw
History Blame Contribute Delete
5.74 kB
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)