Spaces:
Sleeping
Sleeping
Create main.py
Browse files
main.py
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import FastAPI, Header, HTTPException, Request
|
| 2 |
+
import secrets, sqlite3, requests, os
|
| 3 |
+
|
| 4 |
+
app = FastAPI()
|
| 5 |
+
DB_PATH = "/data/keys.db" # Use persistent storage if available
|
| 6 |
+
BRAIN_URL = "https://your-username-gemma-brain.hf.space/completion"
|
| 7 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
| 8 |
+
|
| 9 |
+
# Initialize Database
|
| 10 |
+
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
|
| 11 |
+
conn.execute("CREATE TABLE IF NOT EXISTS keys (api_key TEXT PRIMARY KEY, user_id TEXT)")
|
| 12 |
+
|
| 13 |
+
@app.post("/generate-key")
|
| 14 |
+
async def create_key(user_id: str):
|
| 15 |
+
new_key = f"gemma_max_sk_{secrets.token_urlsafe(16)}"
|
| 16 |
+
conn.execute("INSERT INTO keys VALUES (?, ?)", (new_key, user_id))
|
| 17 |
+
conn.commit()
|
| 18 |
+
return {"api_key": new_key}
|
| 19 |
+
|
| 20 |
+
@app.post("/v1/chat")
|
| 21 |
+
async def proxy_to_brain(request: Request, authorization: str = Header(None)):
|
| 22 |
+
# 1. Check API Key
|
| 23 |
+
key = authorization.replace("Bearer ", "")
|
| 24 |
+
res = conn.execute("SELECT user_id FROM keys WHERE api_key=?", (key,)).fetchone()
|
| 25 |
+
if not res:
|
| 26 |
+
raise HTTPException(status_code=401, detail="Invalid API Key")
|
| 27 |
+
|
| 28 |
+
# 2. Forward to Private Brain
|
| 29 |
+
user_data = await request.json()
|
| 30 |
+
response = requests.post(
|
| 31 |
+
BRAIN_URL,
|
| 32 |
+
json={"prompt": user_data["prompt"], "n_predict": 512},
|
| 33 |
+
headers={"Authorization": f"Bearer {HF_TOKEN}"}
|
| 34 |
+
)
|
| 35 |
+
return response.json()
|