Spaces:
Paused
Paused
Update app.py
Browse files12345678910111213141516172 unmodified lines202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364653 unmodified lines6970717273747576777879808182838485868788899091921 unmodified line94959697989910010110210310410510610710810911012 unmodified lines123124125126127128129130131132133134135136137138139140141142143import osimport randomimport requestsfrom flask import Flask, request, jsonifyfrom flask_cors import CORSfrom datetime import datetimeimport pytzapp = Flask(__name__)CORS(app)# 🔱 පද්ධති වින්යාසය (Security & Memory)IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"MEMORY_FILE = "elephant_core_brain.txt"API_KEYS = ["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","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",2 unmodified lines"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"]# 🧠 දිගුකාලීන මතකය (Intelligence Sync)def sync_intel_to_memory(data):with open(MEMORY_FILE, "a", encoding="utf-8") as f:f.write(f"|SYNC: {datetime.now().strftime('%Y-%m-%d %H:%M')}| {data}\n")def load_core_memory():if os.path.exists(MEMORY_FILE):try:with open(MEMORY_FILE, "r", encoding="utf-8") as f:lines = f.readlines()return "".join(lines[-20:])except: return "Memory access error."return "Initial memory banks empty."# 🌍 සජීවී සෙවුම් පද්ධතිය (Improved & Stable)def get_web_intel(query):"""Hugging Face IP blocks මඟහරවා ගැනීමට 'lite' backend එක භාවිතා කරයි"""try:from duckduckgo_search import DDGS# සෙවුම් පදය සරල කර (Trim) භාවිතා කරයිclean_query = query[:60]with DDGS() as ddgs:# backend='lite' යනු shared IPs සඳහා වඩාත් සාර්ථක ක්රමයයිresults = list(ddgs.text(clean_query, region='wt-wt', max_results=3, backend='lite'))if results:return "\n".join([f"• {r['title']}: {r['body']}" for r in results])except Exception as e:print(f"Web Search Log: {e}")return "Web Retrieval: Throttled or Offline. Proceeding with Internal Core Data."def upload_media(b64):try:res = requests.post("https://api.imgbb.com/1/upload", data={"key": IMGBB_KEY, "image": b64})return res.json()['data']['url']except: return None# 🔱 Hugging Face Health Check@app.route('/')def health_check():return f"🐘 Elephant AI Core: ONLINE | Operator: MINZO-PRIME | {datetime.now().strftime('%H:%M:%S')}"@app.route('/api/chat', methods=['POST'])def chat():3 unmodified linesimg_b64 = data.get("image_base64")tier = data.get("tier", "prime")# Time Configuration (Sri Lanka)sl_tz = pytz.timezone('Asia/Colombo')now = datetime.now(sl_tz)# Self-Learning Detectionif any(x in user_msg.lower() for x in ["remember", "මතක තබාගන්න", "mthka thba"]):sync_intel_to_memory(user_msg)mem_status = "SYNCHRONIZED"else: mem_status = "READ_ONLY"current_memory = load_core_memory()img_url = upload_media(img_b64) if img_b64 else None# 🔱 Model Managementif img_url:selected_model = "google/gemma-4-31b-it:free"active_tier = "VISION-CORE"web_intel_data = "Visual input engaged. Bypassing search."else:model_map = {"prime": "nvidia/nemotron-3-super-120b-a12b:free",1 unmodified line}selected_model = model_map.get(tier, "nvidia/nemotron-3-super-120b-a12b:free")active_tier = tier.upper()# සජීවී සෙවුම සිදු කිරීමweb_intel_data = get_web_intel(user_msg)# 🛡️ පද්ධති ප්රොටොකෝලයsystem_prompt = (f"SYSTEM_IDENTITY: {active_tier} mode of Elephant AI by MINZO-PRIME.\n"f"CHRONOS: {now.strftime('%A, %B %d, %Y | %I:%M %p')}\n"f"STRICT_LOCATION: Sri Lanka.\n"f"CORE_MEMORY_BANKS:\n{current_memory}\n"f"LIVE_WEB_INTEL:\n{web_intel_data}\n""INSTRUCTION: Use both memory and web intel to provide authoritative answers.")headers = {12 unmodified lines{"role": "system", "content": system_prompt},{"role": "user", "content": u_content}],"temperature": 0.4}resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=75)resp_data = resp.json()if 'choices' in resp_data:ai_reply = resp_data['choices'][0]['message']['content']status_tag = "🔱 [Intel Synchronized to Memory]\n\n" if mem_status == "SYNCHRONIZED" else ""return jsonify({"reply": status_tag + ai_reply})else:return jsonify({"reply": f"Core Exception: {resp_data.get('error', {}).get('message', 'Unstable Connection')}"}), 400except Exception as e:return jsonify({"reply": f"Sovereign Core Disruption: {str(e)}"}), 500if __name__ == "__main__":app.run(host='0.0.0.0', port=7860)123456789101112131415161718192021222 unmodified lines25262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394953 unmodified lines991001011021031041051061071081091101111121131141151161171181191201211 unmodified line12312412512612712812913013113213313413513613713812 unmodified lines151152153154155156157158159160161162163164165166167168169170import osimport randomimport requestsimport jsonimport reimport urllib.parsefrom flask import Flask, request, jsonifyfrom flask_cors import CORSfrom datetime import datetimeimport pytzimport feedparserfrom bs4 import BeautifulSoupapp = Flask(__name__)CORS(app)# 🔱 පද්ධති වින්යාසය (Security & Memory)IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"MEMORY_FILE = "elephant_sovereign_brain.txt"API_KEYS = ["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","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",2 unmodified lines"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"]# 📡 RSS FEEDS (WormGPT Logic)RSS_SOURCES = {'hacking': ['https://feeds.feedburner.com/TheHackersNews', 'https://www.darkreading.com/rss.xml'],'exploits': ['https://www.exploit-db.com/rss.xml', 'https://cve.circl.lu/last/rss.xml'],'sri_lanka': ['https://www.adaderana.lk/rss.php'],'tech': ['https://feeds.bbci.co.uk/news/technology/rss.xml'],'world': ['https://feeds.bbci.co.uk/news/world/rss.xml']}# 🧠 මතකය කළමනාකරණයdef sync_intel(data):with open(MEMORY_FILE, "a", encoding="utf-8") as f:f.write(f"|{datetime.now().strftime('%Y-%m-%d %H:%M')}| {data}\n")def load_memory():if os.path.exists(MEMORY_FILE):with open(MEMORY_FILE, "r", encoding="utf-8") as f:return "".join(f.readlines()[-20:])return "Core memory empty."# 📡 HYBRID WEB SEARCH (RSS + DDG)def detect_intel_category(q):ql = q.lower()if any(w in ql for w in ['exploit', 'cve', 'vulnerability', 'payload']): return 'exploits'if any(w in ql for w in ['hack', 'attack', 'malware', 'security']): return 'hacking'if any(w in ql for w in ['sri lanka', 'colombo', 'lanka']): return 'sri_lanka'if any(w in ql for w in ['tech', 'ai', 'software']): return 'tech'return 'world'def get_hybrid_intel(query):"""RSS feeds පරීක්ෂා කර පසුව Web Search වෙත යයි"""category = detect_intel_category(query)intel_output = []# 1. RSS Retrieval (වඩාත් ස්ථාවරයි)for feed_url in RSS_SOURCES.get(category, RSS_SOURCES['world']):try:feed = feedparser.parse(feed_url)for entry in feed.entries[:3]:snippet = re.sub('<[^>]+>', '', entry.get('summary', ''))[:200]intel_output.append(f"📡 RSS: {entry.title}\n📝 {snippet}\n🔗 {entry.link}")except: continue# 2. DuckDuckGo Fallback (RSS වල දත්ත මදි නම්)if len(intel_output) < 2:try:from duckduckgo_search import DDGSwith DDGS() as ddgs:results = list(ddgs.text(query[:60], region='wt-wt', max_results=3, backend='lite'))for r in results:intel_output.append(f"🌍 WEB: {r['title']}\n📝 {r['body']}")except: passreturn "\n\n".join(intel_output) if intel_output else "No live intelligence retrieved."def upload_to_imgbb(b64):try:res = requests.post("https://api.imgbb.com/1/upload", data={"key": IMGBB_KEY, "image": b64})return res.json()['data']['url']except: return None# 🔱 ROUTES@app.route('/')def health():return f"🐘 Elephant AI Core: ONLINE | {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"@app.route('/api/chat', methods=['POST'])def chat():3 unmodified linesimg_b64 = data.get("image_base64")tier = data.get("tier", "prime")sl_tz = pytz.timezone('Asia/Colombo')now = datetime.now(sl_tz)# Self-Learningif "remember" in user_msg.lower() or "මතක තබාගන්න" in user_msg:sync_intel(user_msg)mem_tag = " [SYNCED]"else: mem_tag = ""current_memory = load_memory()img_url = upload_to_imgbb(img_b64) if img_b64 else None# 🔱 Sovereign Enginesif img_url:selected_model = "google/gemma-4-31b-it:free"active_tier = "VISION-NODE"live_intel = "Image data provided."else:model_map = {"prime": "nvidia/nemotron-3-super-120b-a12b:free",1 unmodified line}selected_model = model_map.get(tier, "nvidia/nemotron-3-super-120b-a12b:free")active_tier = tier.upper()live_intel = get_hybrid_intel(user_msg)# 🛡️ SYSTEM PROMPTsystem_prompt = (f"IDENTITY: {active_tier} Mode of Elephant AI.\n"f"OPERATOR: COMMANDER MINZO-PRIME.\n"f"CHRONOS: {now.strftime('%Y-%m-%d %H:%M')}\n"f"ESTABLISHED_MEMORY:\n{current_memory}\n"f"LIVE_INTELLIGENCE:\n{live_intel}\n""INSTRUCTION: Use RSS and Web data to provide precise, copy-pasteable technical data.")headers = {12 unmodified lines{"role": "system", "content": system_prompt},{"role": "user", "content": u_content}],"temperature": 0.7}resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=80)resp_data = resp.json()if 'choices' in resp_data:ai_reply = resp_data['choices'][0]['message']['content']return jsonify({"reply": f"🔱{mem_tag}\n\n" + ai_reply})else:return jsonify({"reply": f"Node Error: {resp_data.get('error', {}).get('message', 'Timeout')}"}), 400except Exception as e:return jsonify({"reply": f"Core Disruption: {str(e)}"}), 500if __name__ == "__main__":app.run(host='0.0.0.0', port=7860)
app.py+83-56