Spaces:
Paused
Paused
Update app.py
Browse files26 unmodified lines272829303132333435363738394041424344451 unmodified line474849505152535455563 unmodified lines6061626364656667686970711 unmodified line7374757677787980818283848586878889909192939495969798991001011021031041051061079 unmodified lines11711811912012112212312412512612712812913013113213313426 unmodified linesdef load_core_memory():if os.path.exists(MEMORY_FILE):with open(MEMORY_FILE, "r", encoding="utf-8") as f:lines = f.readlines()return "".join(lines[-20:])return "Initial memory banks empty."# 🌍 වෙබ් සෙවුම් පද්ධතියdef get_web_intel(query):try:from duckduckgo_search import DDGSwith DDGS() as ddgs:results = list(ddgs.text(query, region='wt-wt', max_results=4))return "\n".join([f"• {r['title']}: {r['body']}" for r in results])except: return "Web Retrieval Mode: Offline"def upload_media(b64):try:1 unmodified linereturn res.json()['data']['url']except: return None# 🔱 Hugging Face Health Check (404 Error එක මඟහරවා ගැනීමට)@app.route('/')def health_check():return "🐘 Elephant AI Core: ONLINE | Operator: MINZO-PRIME | Node: Stable"@app.route('/api/chat', methods=['POST'])def chat():3 unmodified linesimg_b64 = data.get("image_base64")tier = data.get("tier", "prime")# Time Configurationsl_tz = pytz.timezone('Asia/Colombo')now = datetime.now(sl_tz)# Self-Learning Detectionif any(x in user_msg.lower() for x in ["remember", "මතක තබාගන්න"]):sync_intel_to_memory(user_msg)mem_status = "SYNCHRONIZED"else: mem_status = "READ_ONLY"1 unmodified linecurrent_memory = load_core_memory()img_url = upload_media(img_b64) if img_b64 else None# 🔱 Sovereign Model Selection (2026 Engine Upgrades)if img_url:# Gemma 4: Google's 2026 flagship multimodal free modelselected_model = "google/gemma-4-31b-it:free"active_tier = "VISION-NODE"web_intel_data = "Image analysis protocol engaged."else:model_map = {"prime": "nvidia/nemotron-3-super-120b-a12b:free", # 120B High-Reasoning"nexus": "z-ai/glm-4.5-air:free" # 2025 Flagship Air MoE}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.\n"f"OPERATOR: MINZO-PRIME / Specialist Team.\n"f"CHRONOS: {now.strftime('%A, %B %d, %Y | %I:%M %p')}\n"f"CORE_MEMORY_BANKS:\n{current_memory}\n"f"WEB_INTEL:\n{web_intel_data}\n""INSTRUCTION: Use the memory to personalize responses. Be precise and sovereign.")headers = {"Authorization": f"Bearer {random.choice(API_KEYS)}","Content-Type": "application/json","X-Title": "Elephant AI Sovereign"}# Content Assembly9 unmodified lines"temperature": 0.4}resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=70)resp_data = resp.json()if 'choices' in resp_data:ai_reply = resp_data['choices'][0]['message']['content']status_tag = "🔱 [Intel Sync Complete]\n\n" if mem_status == "SYNCHRONIZED" else ""return jsonify({"reply": status_tag + ai_reply})else:return jsonify({"reply": f"Node Error: {resp_data.get('error', {}).get('message', 'Core Overload')}"}), 400except Exception as e:return jsonify({"reply": f"Core Disruption: {str(e)}"}), 500if __name__ == "__main__":app.run(host='0.0.0.0', port=7860)26 unmodified lines272829303132333435363738394041424344454647484950515253541 unmodified line565758596061626364653 unmodified lines6970717273747576777879801 unmodified line8283848586878889909192939495969798991001011021031041051061071081091101111121131141151169 unmodified lines12612712812913013113213313413513613713813914014114214326 unmodified linesdef 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:1 unmodified linereturn 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"1 unmodified linecurrent_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","nexus": "z-ai/glm-4.5-air:free"}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 = {"Authorization": f"Bearer {random.choice(API_KEYS)}","Content-Type": "application/json","HTTP-Referer": "https://huggingface.co/spaces/minzo456/Elephant-AI-Core"}# Content Assembly9 unmodified lines"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)
app.py+35-26