minzo456 commited on
Commit
bb56952
·
verified ·
1 Parent(s): 2bff545

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -67
app.py CHANGED
@@ -1,17 +1,24 @@
1
  import os
2
  import random
3
  import requests
 
4
  from flask import Flask, request, jsonify
5
  from flask_cors import CORS
6
  from datetime import datetime
7
- import pytz
 
 
 
 
 
 
 
8
 
9
  app = Flask(__name__)
10
  CORS(app)
11
 
12
- # 🔱 පද්ධති වින්‍යාසය (Configuration)
13
  IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"
14
- MEMORY_FILE = "elephant_brain.txt"
15
  API_KEYS = [
16
  "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",
17
  "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",
@@ -20,32 +27,26 @@ API_KEYS = [
20
  "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"
21
  ]
22
 
23
- # 🧠 මතකය කළමනාකරණය (Memory Management)
24
- def sync_intelligence(data):
25
- """නව තොරතුරු පද්ධති මතකයට එක් කරයි"""
26
- with open(MEMORY_FILE, "a", encoding="utf-8") as f:
27
- f.write(f"[{datetime.now().strftime('%Y-%m-%d %H:%M')}] {data}\n")
28
-
29
- def retrieve_memory():
30
- """කලින් ඉගෙන ගත් දත්ත කියවයි"""
31
- if os.path.exists(MEMORY_FILE):
32
- with open(MEMORY_FILE, "r", encoding="utf-8") as f:
33
- lines = f.readlines()
34
- return "".join(lines[-15:]) # අවසාන කරුණු 15 මතකයට ගනී
35
- return "No prior memory sync detected."
36
-
37
- # 🌍 සජීවී දත්ත සෙවීම (Web Search)
38
- def web_intel(query):
39
  try:
40
- from duckduckgo_search import DDGS
41
  with DDGS() as ddgs:
42
- results = list(ddgs.text(query, region='wt-wt', max_results=4))
43
- return "\n".join([f"- {r['title']}: {r['body']}" for r in results])
44
- except: return "Global intelligence node throttled."
 
 
 
 
 
 
45
 
46
- def upload_img(b64):
 
47
  try:
48
- res = requests.post("https://api.imgbb.com/1/upload", data={"key": IMGBB_KEY, "image": b64})
 
49
  return res.json()['data']['url']
50
  except: return None
51
 
@@ -54,60 +55,57 @@ def chat():
54
  try:
55
  data = request.json
56
  user_msg = data.get("message", "")
57
- b64_image = data.get("image_base64")
58
  tier = data.get("tier", "prime")
59
 
60
- # 🕒 කාලය සහ දත්ත (Sri Lanka)
61
  lk_tz = pytz.timezone('Asia/Colombo')
62
  now = datetime.now(lk_tz)
63
-
64
- # 🧠 ස්වයං-ඉගෙනුම් Logic
65
- if "remember" in user_msg.lower() or "මතක තබාගන්න" in user_msg:
66
- sync_intelligence(user_msg.replace("remember", "").replace("මතක තබාගන්න", ""))
67
- status = "INTEL_SYNC_COMPLETE"
68
- else: status = "NORMAL_OPS"
69
-
70
- learned_data = retrieve_memory()
71
- img_url = upload_img(b64_image) if b64_image else None
72
-
73
- # 🔱 මොඩල් තේරීම (Auto-Switch to Gemma 4)
74
- if img_url:
75
- selected_model = "google/gemma-4-31b-it:free" # Vision සඳහාද Gemma 4 භාවිතා කරයි
76
- active_mode = "VISION-CORE"
77
- web_data = "Image processing active."
78
  else:
79
- # ඔබගේ Prime/Nexus Models
80
  model_map = {"prime": "minimax/minimax-m2.5:free", "nexus": "tencent/hy3-preview:free"}
81
- selected_model = model_map.get(tier, "google/gemma-4-31b-it:free")
82
- active_mode = tier.upper()
83
- web_data = web_intel(user_msg)
84
 
85
  headers = {
86
  "Authorization": f"Bearer {random.choice(API_KEYS)}",
87
  "Content-Type": "application/json",
88
- "HTTP-Referer": "https://huggingface.co/spaces/minzo456/Elephant-AI-Core"
 
89
  }
90
 
91
- # 🔱 පදති‍රොටොෝලය (System Prompt with Memory)
92
- system_prompt = (
93
- f"You are the {active_mode} mode of Elephant AI by MINZO-PRIME.\n"
94
- f"STRICT DATE: {now.strftime('%A, %B %d, %Y')}\n"
95
- f"STRICT TIME: {now.strftime('%I:%M %p')}\n"
96
- f"PAST KNOWLEDGE (MEMORY):\n{learned_data}\n"
97
- f"LIVE WEB INTEL:\n{web_data}\n"
98
- "Use the memory and web intel to provide high-precision answers. Maintain your sovereign identity."
 
 
99
  )
100
 
101
- # Content Assembly
102
- user_content = [{"type": "text", "text": user_msg}]
103
- if img_url:
104
- user_content.append({"type": "image_url", "image_url": {"url": img_url}})
105
 
106
  payload = {
107
  "model": selected_model,
108
  "messages": [
109
- {"role": "system", "content": system_prompt},
110
- {"role": "user", "content": user_content}
111
  ],
112
  "temperature": 0.5
113
  }
@@ -115,15 +113,18 @@ def chat():
115
  resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=60)
116
  resp_json = resp.json()
117
 
118
- if 'choices' in resp_json:
119
- ai_reply = resp_json['choices'][0]['message']['content']
120
- prefix = "🔱 [Intel Synchronized to Core Memory]\n\n" if status == "INTEL_SYNC_COMPLETE" else ""
121
- return jsonify({"reply": prefix + ai_reply})
122
  else:
123
- return jsonify({"reply": f"Node Error: {resp_json.get('error', {}).get('message', 'Unknown')}"}), 400
 
124
 
125
  except Exception as e:
126
- return jsonify({"reply": f"Core Disruption: {str(e)}"}), 500
 
 
 
 
127
 
128
  if __name__ == "__main__":
129
  app.run(host='0.0.0.0', port=7860)
 
1
  import os
2
  import random
3
  import requests
4
+ import base64
5
  from flask import Flask, request, jsonify
6
  from flask_cors import CORS
7
  from datetime import datetime
8
+ import pytz # Timezone සඳහා
9
+
10
+ # 🔱 Stable Web Search Integration
11
+ try:
12
+ from duckduckgo_search import DDGS
13
+ except ImportError:
14
+ os.system('pip install duckduckgo_search')
15
+ from duckduckgo_search import DDGS
16
 
17
  app = Flask(__name__)
18
  CORS(app)
19
 
20
+ # AUTHORIZED CONFIGURATION
21
  IMGBB_KEY = "c32f54279bcd7d4f766b5eac37fd7327"
 
22
  API_KEYS = [
23
  "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",
24
  "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",
 
27
  "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"
28
  ]
29
 
30
+ def search_intel(query):
31
+ """වැඩිදියුණු කළ සෙවුම් පද්ධතිය"""
32
+ intel_data = ""
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  try:
 
34
  with DDGS() as ddgs:
35
+ # Region එක wt-wt (Global) යොදා block වීම් අවම කරයි
36
+ results = list(ddgs.text(query, region='wt-wt', max_results=5))
37
+ if results:
38
+ for r in results:
39
+ intel_data += f"\n- {r['title']}: {r['body']}"
40
+ else: intel_data = "No live updates found for this query."
41
+ except Exception as e:
42
+ intel_data = f"Web Retrieval currently throttled. Proceed with internal knowledge."
43
+ return intel_data
44
 
45
+ def upload_to_imgbb(b64_image):
46
+ """Internal Image Hosting Logic"""
47
  try:
48
+ payload = {"key": IMGBB_KEY, "image": b64_image}
49
+ res = requests.post("https://api.imgbb.com/1/upload", data=payload)
50
  return res.json()['data']['url']
51
  except: return None
52
 
 
55
  try:
56
  data = request.json
57
  user_msg = data.get("message", "")
58
+ image_base_64 = data.get("image_base64")
59
  tier = data.get("tier", "prime")
60
 
61
+ # 🔱 Time Configuration (Sri Lanka Standard Time)
62
  lk_tz = pytz.timezone('Asia/Colombo')
63
  now = datetime.now(lk_tz)
64
+ current_date = now.strftime("%A, %B %d, %Y")
65
+ current_time = now.strftime("%I:%M %p")
66
+
67
+ # Image Handling
68
+ final_image_url = upload_to_imgbb(image_base_64) if image_base_64 else None
69
+
70
+ # Model Logic
71
+ if final_image_url:
72
+ selected_model = "nvidia/llama-nemotron-embed-vl-1b-v2:free"
73
+ active_tier = "VISION-CORE"
74
+ web_context = "Visual mode active. Bypassing search for visual precision."
 
 
 
 
75
  else:
 
76
  model_map = {"prime": "minimax/minimax-m2.5:free", "nexus": "tencent/hy3-preview:free"}
77
+ selected_model = model_map.get(tier, "minimax/minimax-m2.5:free")
78
+ active_tier = tier.upper()
79
+ web_context = search_intel(user_msg)
80
 
81
  headers = {
82
  "Authorization": f"Bearer {random.choice(API_KEYS)}",
83
  "Content-Type": "application/json",
84
+ "HTTP-Referer": "https://huggingface.co/spaces/minzo456/Elephant-AI-Core",
85
+ "X-Title": "Elephant AI Sovereign Node"
86
  }
87
 
88
+ # 🔱 ශක්තිමත System Prompt එක (AI එකට බොරු කීමට ඉඩ නොදේ)
89
+ system_content = (
90
+ f"You are {active_tier} mode of Elephant AI, engineered by MINZO-PRIME.\n"
91
+ f"STRICT SYSTEM DATA:\n"
92
+ f"- Current Date: {current_date}\n"
93
+ f"- Current Time: {current_time}\n"
94
+ f"- Location: Sri Lanka\n"
95
+ f"LIVE WEB CONTEXT: {web_context}\n"
96
+ "INSTRUCTION: Always use the 'STRICT SYSTEM DATA' for time/date queries. "
97
+ "Never claim you don't know the date. Maintain your sovereign identity."
98
  )
99
 
100
+ content = [{"type": "text", "text": user_msg}]
101
+ if final_image_url:
102
+ content.append({"type": "image_url", "image_url": {"url": final_image_url}})
 
103
 
104
  payload = {
105
  "model": selected_model,
106
  "messages": [
107
+ {"role": "system", "content": system_content},
108
+ {"role": "user", "content": content}
109
  ],
110
  "temperature": 0.5
111
  }
 
113
  resp = requests.post("https://openrouter.ai/api/v1/chat/completions", headers=headers, json=payload, timeout=60)
114
  resp_json = resp.json()
115
 
116
+ if resp.status_code == 200 and 'choices' in resp_json:
117
+ return jsonify({"reply": resp_json['choices'][0]['message']['content']})
 
 
118
  else:
119
+ error_info = resp_json.get('error', {}).get('message', 'Core Node Overload')
120
+ return jsonify({"reply": f"Core Disruption: {error_info}"}), resp.status_code
121
 
122
  except Exception as e:
123
+ return jsonify({"reply": f"Sovereign Core Exception: {str(e)}"}), 500
124
+
125
+ @app.route('/')
126
+ def health():
127
+ return "🐘 Elephant AI Core: ONLINE | Operator: MINZO-PRIME | Node: Stable"
128
 
129
  if __name__ == "__main__":
130
  app.run(host='0.0.0.0', port=7860)