MINZO4546 commited on
Commit
13ded7d
·
verified ·
1 Parent(s): 5cac8e2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +1 -104
app.py CHANGED
@@ -1,104 +1 @@
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
- from transformers import AutoModelForCausalLM, AutoTokenizer
7
- from duckduckgo_search import DDGS
8
-
9
- # 🔱 Server එකට "app" කියන නමම අවශ්‍යයි
10
- app = FastAPI()
11
-
12
- app.add_middleware(
13
- CORSMiddleware,
14
- allow_origins=["*"],
15
- allow_methods=["*"],
16
- allow_headers=["*"],
17
- )
18
-
19
- # --- Database & Config ---
20
- API_KEYS_DB = {
21
- "ELE-PRIME-ADMIN-SYS": {"limit": 10000, "used": 0, "status": "active"}
22
- }
23
- ADMIN_SECRET = "MINZO-SECRET-2026"
24
-
25
- # --- AI Model (Gemma-3-1B-it) ---
26
- model_id = "google/gemma-3-1b-it"
27
- HF_TOKEN = os.getenv("HF_TOKEN")
28
-
29
- print(f"🐘 Elephant Node v3.7 Loading: {model_id}...")
30
-
31
- tokenizer = AutoTokenizer.from_pretrained(model_id, token=HF_TOKEN)
32
-
33
- # 🔱 [Fix] torch_dtype වෙනුවට dtype පාවිච්චි කරන ලදී
34
- model = AutoModelForCausalLM.from_pretrained(
35
- model_id,
36
- dtype=torch.bfloat16,
37
- device_map="cpu",
38
- token=HF_TOKEN
39
- )
40
-
41
- # --- Data Models ---
42
- class KeyRequest(BaseModel):
43
- admin_pass: str
44
- new_key: str
45
- limit: int = 100
46
-
47
- # --- API Endpoints ---
48
- @app.get("/")
49
- def home():
50
- return {"status": "Elephant Pro Active", "model": "Gemma-3-1B"}
51
-
52
- @app.post("/admin/add-key")
53
- async def add_key(data: KeyRequest):
54
- if data.admin_pass != ADMIN_SECRET:
55
- raise HTTPException(status_code=401)
56
- API_KEYS_DB[data.new_key] = {"limit": data.limit, "used": 0, "status": "active"}
57
- return {"message": "Key Activated"}
58
-
59
- @app.get("/v1/usage")
60
- async def get_usage(x_api_key: str = Header(None)):
61
- if not x_api_key or x_api_key not in API_KEYS_DB:
62
- raise HTTPException(status_code=403, detail="Invalid Key")
63
- info = API_KEYS_DB[x_api_key]
64
- return {
65
- "used": info["used"],
66
- "limit": info["limit"]
67
- }
68
-
69
- @app.post("/v1/chat")
70
- async def chat(message: dict, x_api_key: str = Header(None)):
71
- if not x_api_key or x_api_key not in API_KEYS_DB:
72
- raise HTTPException(status_code=403)
73
-
74
- key_info = API_KEYS_DB[x_api_key]
75
- if key_info["used"] >= key_info["limit"]:
76
- raise HTTPException(status_code=429, detail="Limit Reached")
77
-
78
- query = message.get("query", "")
79
-
80
- # 2026 Web Search Logic
81
- context = ""
82
- try:
83
- if any(w in query.lower() for w in ["today", "now", "2026"]):
84
- with DDGS() as ddgs:
85
- context = "\n".join([r['body'] for r in ddgs.text(query, max_results=2)])
86
- except: pass
87
-
88
- # AI Inference
89
- msgs = [
90
- {"role": "system", "content": f"Elephant AI by MINZO-PRIME. 2026 Edition. Context: {context}"},
91
- {"role": "user", "content": query}
92
- ]
93
-
94
- text = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
95
- inputs = tokenizer([text], return_tensors="pt").to("cpu")
96
-
97
- with torch.no_grad():
98
- ids = model.generate(inputs.input_ids, max_new_tokens=300, temperature=0.7, do_sample=True)
99
- full_ans = tokenizer.batch_decode(ids, skip_special_tokens=True)[0]
100
- ans = full_ans.split("model")[-1].strip()
101
-
102
- API_KEYS_DB[x_api_key]["used"] += 1
103
- return {"reply": ans, "usage": API_KEYS_DB[x_api_key]["used"]}
104
-
 
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