MINZO4546 commited on
Commit
83957eb
·
verified ·
1 Parent(s): 4eb1f37

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +97 -1
app.py CHANGED
@@ -1 +1,97 @@
1
- from fastapi import FastAPI, Header, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelimport torchimport osimport jsonimport datetimefrom transformers import AutoModelForCausalLM, AutoTokenizerfrom duckduckgo_search import DDGSapp = FastAPI()# CORS Fix for Dashboard connectivityapp.add_middleware( CORSMiddleware, allow_origins=["*"], allow_methods=["*"], allow_headers=["*"],)# --- Database & Config ---API_KEYS_DB = { "ELE-PRIME-ADMIN-SYS": {"limit": 10000, "used": 0, "status": "active"}}ADMIN_SECRET = "MINZO-SECRET-2026"LEARNING_VAULT = "neural_learning_data.jsonl"# --- AI Model (Qwen-2.5-1.5B) ---model_id = "Qwen/Qwen2.5-1.5B-Instruct"print("🐘 Elephant Node v3.7 Loading...")tokenizer = AutoTokenizer.from_pretrained(model_id)model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", device_map="cpu")# --- Data Models ---class KeyRequest(BaseModel): admin_pass: str new_key: str limit: int = 100# --- API Endpoints ---@app.get("/")def home(): return {"status": "Elephant Pro Active", "keys": len(API_KEYS_DB)}@app.post("/admin/add-key")async def add_key(data: KeyRequest): if data.admin_pass != ADMIN_SECRET: raise HTTPException(status_code=401) API_KEYS_DB[data.new_key] = {"limit": data.limit, "used": 0, "status": "active"} return {"message": "Key Activated"}@app.get("/v1/usage")async def get_usage(x_api_key: str = Header(None)): """Key එකේ පාවිච්චිය පරීක්ෂා කිරීමේ Endpoint එක""" if not x_api_key or x_api_key not in API_KEYS_DB: raise HTTPException(status_code=403, detail="Invalid Key") info = API_KEYS_DB[x_api_key] return { "used": info["used"], "limit": info["limit"], "percentage": (info["used"] / info["limit"]) * 100 if info["limit"] > 0 else 0 }@app.post("/v1/chat")async def chat(message: dict, x_api_key: str = Header(None)): if x_api_key not in API_KEYS_DB: raise HTTPException(status_code=403) key_info = API_KEYS_DB[x_api_key] if key_info["used"] >= key_info["limit"]: raise HTTPException(status_code=429, detail="Limit Reached") query = message.get("query", "") # 2026 Web Search Logic context = "" if any(w in query.lower() for w in ["today", "now", "2026"]): try: with DDGS() as ddgs: context = "\n".join([r['body'] for r in ddgs.text(query, max_results=2)]) except: pass # AI Inference msgs = [{"role": "system", "content": f"Elephant AI. 2026 mode. Context: {context}"}, {"role": "user", "content": query}] text = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True) inputs = tokenizer([text], return_tensors="pt").to("cpu") with torch.no_grad(): ids = model.generate(inputs.input_ids, max_new_tokens=256) ans = tokenizer.batch_decode(ids, skip_special_tokens=True)[0].split("assistant")[-1].strip() # Update Stats API_KEYS_DB[x_api_key]["used"] += 1 return {"reply": ans, "usage": API_KEYS_DB[x_api_key]["used"]}main = app
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, Header, HTTPException
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from pydantic import BaseModel
4
+ 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 Fix for Dashboard connectivity
14
+ app.add_middleware(
15
+ CORSMiddleware,
16
+ allow_origins=["*"],
17
+ allow_methods=["*"],
18
+ allow_headers=["*"],
19
+ )
20
+
21
+ # --- Database & Config ---
22
+ API_KEYS_DB = {
23
+ "ELE-PRIME-ADMIN-SYS": {"limit": 10000, "used": 0, "status": "active"}
24
+ }
25
+ ADMIN_SECRET = "MINZO-SECRET-2026"
26
+ LEARNING_VAULT = "neural_learning_data.jsonl"
27
+
28
+ # --- AI Model (Qwen-2.5-1.5B) ---
29
+ model_id = "Qwen/Qwen2.5-1.5B-Instruct"
30
+ print("🐘 Elephant Node v3.7 Loading...")
31
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
32
+ model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", device_map="cpu")
33
+
34
+ # --- Data Models ---
35
+ class KeyRequest(BaseModel):
36
+ admin_pass: str
37
+ new_key: str
38
+ limit: int = 100
39
+
40
+ # --- API Endpoints ---
41
+
42
+ @app.get("/")
43
+ def home():
44
+ return {"status": "Elephant Pro Active", "keys": len(API_KEYS_DB)}
45
+
46
+ @app.post("/admin/add-key")
47
+ async def add_key(data: KeyRequest):
48
+ if data.admin_pass != ADMIN_SECRET:
49
+ raise HTTPException(status_code=401)
50
+ API_KEYS_DB[data.new_key] = {"limit": data.limit, "used": 0, "status": "active"}
51
+ return {"message": "Key Activated"}
52
+
53
+ @app.get("/v1/usage")
54
+ async def get_usage(x_api_key: str = Header(None)):
55
+ """Key එකේ පාවිච්චිය පරීක්ෂා කිරීමේ Endpoint එක"""
56
+ if not x_api_key or x_api_key not in API_KEYS_DB:
57
+ raise HTTPException(status_code=403, detail="Invalid Key")
58
+ info = API_KEYS_DB[x_api_key]
59
+ return {
60
+ "used": info["used"],
61
+ "limit": info["limit"],
62
+ "percentage": (info["used"] / info["limit"]) * 100 if info["limit"] > 0 else 0
63
+ }
64
+
65
+ @app.post("/v1/chat")
66
+ async def chat(message: dict, x_api_key: str = Header(None)):
67
+ if x_api_key not in API_KEYS_DB:
68
+ raise HTTPException(status_code=403)
69
+
70
+ key_info = API_KEYS_DB[x_api_key]
71
+ if key_info["used"] >= key_info["limit"]:
72
+ raise HTTPException(status_code=429, detail="Limit Reached")
73
+
74
+ query = message.get("query", "")
75
+
76
+ # 2026 Web Search Logic
77
+ context = ""
78
+ if any(w in query.lower() for w in ["today", "now", "2026"]):
79
+ try:
80
+ with DDGS() as ddgs:
81
+ context = "\n".join([r['body'] for r in ddgs.text(query, max_results=2)])
82
+ except: pass
83
+
84
+ # AI Inference
85
+ msgs = [{"role": "system", "content": f"Elephant AI. 2026 mode. Context: {context}"}, {"role": "user", "content": query}]
86
+ text = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
87
+ inputs = tokenizer([text], return_tensors="pt").to("cpu")
88
+
89
+ with torch.no_grad():
90
+ ids = model.generate(inputs.input_ids, max_new_tokens=256)
91
+ ans = tokenizer.batch_decode(ids, skip_special_tokens=True)[0].split("assistant")[-1].strip()
92
+
93
+ # Update Stats
94
+ API_KEYS_DB[x_api_key]["used"] += 1
95
+ return {"reply": ans, "usage": API_KEYS_DB[x_api_key]["used"]}
96
+
97
+ main = app