Spaces:
Runtime error
Runtime error
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 re
|
| 8 |
+
import uuid
|
| 9 |
+
import secrets
|
| 10 |
+
import datetime
|
| 11 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 12 |
+
from duckduckgo_search import DDGS
|
| 13 |
+
|
| 14 |
+
app = FastAPI()
|
| 15 |
+
|
| 16 |
+
app.add_middleware(
|
| 17 |
+
CORSMiddleware,
|
| 18 |
+
allow_origins=["*"],
|
| 19 |
+
allow_methods=["*"],
|
| 20 |
+
allow_headers=["*"],
|
| 21 |
+
)
|
| 22 |
+
|
| 23 |
+
# --- Database & Config ---
|
| 24 |
+
# ආරම්භක Keys
|
| 25 |
+
API_KEYS_DB = {
|
| 26 |
+
"ELE-PRIME-ADMIN-SYS": {"limit": 10000, "used": 0, "status": "active"},
|
| 27 |
+
"ELE-PRIME-YG5EPZFQ": {"limit": 5000, "used": 0, "status": "active"}
|
| 28 |
+
}
|
| 29 |
+
ADMIN_SECRET = "MINZO-SECRET-2026"
|
| 30 |
+
|
| 31 |
+
# --- AI Model ---
|
| 32 |
+
model_id = "google/gemma-3-1b-it"
|
| 33 |
+
print(f"🔱 INACHI-CORE: Loading {model_id}...")
|
| 34 |
+
|
| 35 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 36 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", device_map="cpu")
|
| 37 |
+
|
| 38 |
+
# --- Data Models ---
|
| 39 |
+
class AdminRequest(BaseModel):
|
| 40 |
+
admin_pass: str
|
| 41 |
+
limit: int = 1000
|
| 42 |
+
|
| 43 |
+
# --- API Endpoints ---
|
| 44 |
+
|
| 45 |
+
@app.get("/")
|
| 46 |
+
def home():
|
| 47 |
+
return {"status": "Elephant Pro Active", "active_keys": len(API_KEYS_DB)}
|
| 48 |
+
|
| 49 |
+
# 🔱 අලුතින් Key එකක් Auto-Generate කරන Endpoint එක
|
| 50 |
+
@app.post("/v1/generate-key")
|
| 51 |
+
async def generate_key(data: AdminRequest):
|
| 52 |
+
if data.admin_pass != ADMIN_SECRET:
|
| 53 |
+
raise HTTPException(status_code=401, detail="Unauthorized Specialist Access!")
|
| 54 |
+
|
| 55 |
+
# Random Key එකක් නිර්මාණය කිරීම (උදා: ELE-PRIME-X8A2...)
|
| 56 |
+
new_key = f"ELE-PRIME-{secrets.token_hex(4).upper()}"
|
| 57 |
+
API_KEYS_DB[new_key] = {"limit": data.limit, "used": 0, "status": "active"}
|
| 58 |
+
|
| 59 |
+
return {
|
| 60 |
+
"message": "New Specialist Key Activated",
|
| 61 |
+
"api_key": new_key,
|
| 62 |
+
"limit": data.limit
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
@app.post("/v1/chat")
|
| 66 |
+
async def chat(message: dict, x_api_key: str = Header(None)):
|
| 67 |
+
if not x_api_key or x_api_key not in API_KEYS_DB:
|
| 68 |
+
raise HTTPException(status_code=403, detail="Access Denied")
|
| 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 |
+
# Web Search
|
| 77 |
+
context = ""
|
| 78 |
+
if any(w in query.lower() for w in ["today", "now", "2026", "අද"]):
|
| 79 |
+
try:
|
| 80 |
+
with DDGS() as ddgs:
|
| 81 |
+
results = list(ddgs.text(query, max_results=2))
|
| 82 |
+
context = "\n".join([r['body'] for r in results])
|
| 83 |
+
except: pass
|
| 84 |
+
|
| 85 |
+
# 🔱 Language Adaptive System Instruction
|
| 86 |
+
system_instruction = (
|
| 87 |
+
"You are Elephant AI (Inachi-Core), an expert assistant for Specialist MINZO-PRIME. "
|
| 88 |
+
"Respond in the language used by the user (Sinhala or English). "
|
| 89 |
+
f"Real-time Context: {context}"
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
msgs = [
|
| 93 |
+
{"role": "system", "content": system_instruction},
|
| 94 |
+
{"role": "user", "content": query}
|
| 95 |
+
]
|
| 96 |
+
|
| 97 |
+
text = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
|
| 98 |
+
inputs = tokenizer([text], return_tensors="pt").to("cpu")
|
| 99 |
+
|
| 100 |
+
with torch.no_grad():
|
| 101 |
+
outputs = model.generate(
|
| 102 |
+
inputs.input_ids,
|
| 103 |
+
max_new_tokens=512,
|
| 104 |
+
temperature=0.6,
|
| 105 |
+
top_p=0.9,
|
| 106 |
+
do_sample=True,
|
| 107 |
+
pad_token_id=tokenizer.eos_token_id
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
full_response = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]
|
| 111 |
+
ans = full_response.split("assistant")[-1].strip()
|
| 112 |
+
|
| 113 |
+
# Cleaning Logic
|
| 114 |
+
if "</think>" in ans: ans = ans.split("</think>")[-1].strip()
|
| 115 |
+
ans = ans.replace("Ċ", "\n").replace("Ġ", " ")
|
| 116 |
+
ans = re.sub(r' +', ' ', ans).strip()
|
| 117 |
+
|
| 118 |
+
API_KEYS_DB[x_api_key]["used"] += 1
|
| 119 |
+
return {"reply": ans, "usage": API_KEYS_DB[x_api_key]["used"]}
|
| 120 |
+
|
| 121 |
+
main = app
|