Update app.py
Browse files
app.py
CHANGED
|
@@ -5,12 +5,12 @@ import torch
|
|
| 5 |
import os
|
| 6 |
import json
|
| 7 |
import datetime
|
| 8 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 9 |
from duckduckgo_search import DDGS
|
| 10 |
|
| 11 |
app = FastAPI()
|
| 12 |
|
| 13 |
-
# CORS
|
| 14 |
app.add_middleware(
|
| 15 |
CORSMiddleware,
|
| 16 |
allow_origins=["*"],
|
|
@@ -18,31 +18,21 @@ app.add_middleware(
|
|
| 18 |
allow_headers=["*"],
|
| 19 |
)
|
| 20 |
|
| 21 |
-
# ---
|
| 22 |
-
API_KEYS_DB = {
|
| 23 |
-
"ELE-PRIME-ADMIN-SYS": {"credits": 999999, "status": "active"}
|
| 24 |
-
}
|
| 25 |
ADMIN_SECRET = "MINZO-SECRET-2026"
|
| 26 |
-
LEARNING_VAULT_PATH = "neural_learning_data.jsonl"
|
| 27 |
|
| 28 |
-
# ---
|
| 29 |
-
|
| 30 |
-
|
| 31 |
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 35 |
-
bnb_4bit_quant_type="nf4",
|
| 36 |
-
bnb_4bit_use_double_quant=True,
|
| 37 |
-
)
|
| 38 |
-
|
| 39 |
-
print("🐘 Elephant Learning Engine Loading...")
|
| 40 |
-
tokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN)
|
| 41 |
model = AutoModelForCausalLM.from_pretrained(
|
| 42 |
model_id,
|
| 43 |
-
|
| 44 |
-
device_map="
|
| 45 |
-
token=HF_TOKEN
|
| 46 |
)
|
| 47 |
|
| 48 |
# --- Helpers ---
|
|
@@ -57,72 +47,52 @@ def get_live_data(query):
|
|
| 57 |
return "\n".join(results)
|
| 58 |
except: return ""
|
| 59 |
|
| 60 |
-
# 🧠 CONTINUOUS LEARNING FUNCTION
|
| 61 |
-
# පද්ධතිය විසින් අලුත් දැනුම ගබඩා කරගන්නා ආකාරය
|
| 62 |
def capture_learning_data(query, context, response, key_id):
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
"
|
| 66 |
-
"
|
| 67 |
-
"
|
| 68 |
-
"
|
| 69 |
-
"trained_output": response
|
| 70 |
}
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
f.write(json.dumps(learning_entry) + "\n")
|
| 74 |
-
print(f"📊 Neural Data Captured via {key_id}")
|
| 75 |
|
| 76 |
# --- Endpoints ---
|
| 77 |
|
| 78 |
@app.get("/")
|
| 79 |
-
def
|
| 80 |
-
|
| 81 |
-
learning_count = 0
|
| 82 |
-
if os.path.exists(LEARNING_VAULT_PATH):
|
| 83 |
-
with open(LEARNING_VAULT_PATH, "r") as f:
|
| 84 |
-
learning_count = sum(1 for line in f)
|
| 85 |
-
|
| 86 |
-
return {
|
| 87 |
-
"status": "Elephant AI Node 2026 Live",
|
| 88 |
-
"active_keys": len(API_KEYS_DB),
|
| 89 |
-
"learning_entries_captured": learning_count
|
| 90 |
-
}
|
| 91 |
|
| 92 |
@app.post("/admin/add-key")
|
| 93 |
-
async def
|
| 94 |
-
if data.admin_pass != ADMIN_SECRET:
|
| 95 |
-
raise HTTPException(status_code=401, detail="Unauthorized Admin Access")
|
| 96 |
API_KEYS_DB[data.new_key] = {"credits": 5000, "status": "active"}
|
| 97 |
-
return {"message":
|
| 98 |
|
| 99 |
@app.post("/v1/chat")
|
| 100 |
-
async def
|
| 101 |
-
if x_api_key not in API_KEYS_DB:
|
| 102 |
-
raise HTTPException(status_code=403, detail="Invalid API Key")
|
| 103 |
|
| 104 |
-
|
| 105 |
-
context = ""
|
| 106 |
-
|
| 107 |
-
#
|
| 108 |
-
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
-
full_prompt = f"System: Year 2026. Context: {context}\nUser: {user_query}\nAssistant:"
|
| 112 |
-
inputs = tokenizer(full_prompt, return_tensors="pt").to("cuda")
|
| 113 |
-
|
| 114 |
with torch.no_grad():
|
| 115 |
-
|
|
|
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
capture_learning_data(
|
| 121 |
-
|
| 122 |
-
return {
|
| 123 |
-
"reply": response,
|
| 124 |
-
"key_id": x_api_key,
|
| 125 |
-
"learning_status": "synced"
|
| 126 |
-
}
|
| 127 |
|
| 128 |
main = app
|
|
|
|
| 5 |
import os
|
| 6 |
import json
|
| 7 |
import datetime
|
| 8 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 9 |
from duckduckgo_search import DDGS
|
| 10 |
|
| 11 |
app = FastAPI()
|
| 12 |
|
| 13 |
+
# CORS Fix
|
| 14 |
app.add_middleware(
|
| 15 |
CORSMiddleware,
|
| 16 |
allow_origins=["*"],
|
|
|
|
| 18 |
allow_headers=["*"],
|
| 19 |
)
|
| 20 |
|
| 21 |
+
# --- Neural Vault Setup ---
|
| 22 |
+
API_KEYS_DB = {"ELE-PRIME-ADMIN-SYS": {"credits": 999999, "status": "active"}}
|
|
|
|
|
|
|
| 23 |
ADMIN_SECRET = "MINZO-SECRET-2026"
|
| 24 |
+
LEARNING_VAULT_PATH = "neural_learning_data.jsonl"
|
| 25 |
|
| 26 |
+
# --- New Model Setup (CPU Optimized) ---
|
| 27 |
+
# Qwen 1.5B එක Mistral වලට වඩා 5 ගුණයකට වඩා සැහැල්ලුයි
|
| 28 |
+
model_id = "Qwen/Qwen2.5-1.5B-Instruct"
|
| 29 |
|
| 30 |
+
print("🐘 Elephant Light-Engine Loading on CPU...")
|
| 31 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
model = AutoModelForCausalLM.from_pretrained(
|
| 33 |
model_id,
|
| 34 |
+
torch_dtype="auto", # CPU එකට ගැලපෙන පරිදි auto-select වේ
|
| 35 |
+
device_map="cpu" # GPU නැති නිසා අනිවාර්යයෙන් CPU ලෙස දිය යුතුයි
|
|
|
|
| 36 |
)
|
| 37 |
|
| 38 |
# --- Helpers ---
|
|
|
|
| 47 |
return "\n".join(results)
|
| 48 |
except: return ""
|
| 49 |
|
|
|
|
|
|
|
| 50 |
def capture_learning_data(query, context, response, key_id):
|
| 51 |
+
entry = {
|
| 52 |
+
"timestamp": str(datetime.datetime.now()),
|
| 53 |
+
"key": key_id,
|
| 54 |
+
"q": query,
|
| 55 |
+
"ctx": context,
|
| 56 |
+
"ans": response
|
|
|
|
| 57 |
}
|
| 58 |
+
with open(LEARNING_VAULT_PATH, "a") as f:
|
| 59 |
+
f.write(json.dumps(entry) + "\n")
|
|
|
|
|
|
|
| 60 |
|
| 61 |
# --- Endpoints ---
|
| 62 |
|
| 63 |
@app.get("/")
|
| 64 |
+
def status():
|
| 65 |
+
return {"status": "Elephant-Qwen Node Active", "engine": "Qwen-2.5-1.5B"}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
|
| 67 |
@app.post("/admin/add-key")
|
| 68 |
+
async def add_key(data: NewKeyRequest):
|
| 69 |
+
if data.admin_pass != ADMIN_SECRET: raise HTTPException(status_code=401)
|
|
|
|
| 70 |
API_KEYS_DB[data.new_key] = {"credits": 5000, "status": "active"}
|
| 71 |
+
return {"message": "Key Registered"}
|
| 72 |
|
| 73 |
@app.post("/v1/chat")
|
| 74 |
+
async def chat(message: dict, x_api_key: str = Header(None)):
|
| 75 |
+
if x_api_key not in API_KEYS_DB: raise HTTPException(status_code=403)
|
|
|
|
| 76 |
|
| 77 |
+
query = message.get("query", "")
|
| 78 |
+
context = get_live_data(query) if any(w in query.lower() for w in ["now", "2026", "today"]) else ""
|
| 79 |
+
|
| 80 |
+
# Qwen Chat Template එක භාවිතය
|
| 81 |
+
messages = [
|
| 82 |
+
{"role": "system", "content": f"You are Elephant AI. Current year: 2026. Context: {context}"},
|
| 83 |
+
{"role": "user", "content": query}
|
| 84 |
+
]
|
| 85 |
+
text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
|
| 86 |
+
model_inputs = tokenizer([text], return_tensors="pt").to("cpu")
|
| 87 |
|
|
|
|
|
|
|
|
|
|
| 88 |
with torch.no_grad():
|
| 89 |
+
generated_ids = model.generate(model_inputs.input_ids, max_new_tokens=512)
|
| 90 |
+
response = tokenizer.batch_decode(generated_ids, skip_special_tokens=True)[0]
|
| 91 |
|
| 92 |
+
# පද්ධතියේ පිළිතුර පිරිසිදු කිරීම
|
| 93 |
+
clean_response = response.split("assistant")[-1].strip()
|
| 94 |
+
|
| 95 |
+
capture_learning_data(query, context, clean_response, x_api_key)
|
| 96 |
+
return {"reply": clean_response, "key_id": x_api_key}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 97 |
|
| 98 |
main = app
|