Spaces:
Running
Running
File size: 10,703 Bytes
5db984b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 | # app.py in GATEWAY Space
import os
from flask import Flask, request, jsonify, Response, stream_with_context
from flask_cors import CORS
import requests
from datetime import timedelta
from flask_jwt_extended import (
JWTManager,
create_access_token,
jwt_required,
get_jwt_identity,
)
app = Flask(__name__)
CORS(app)
# Strong secret key via HF Space secret
app.config["JWT_SECRET_KEY"] = os.environ.get("JWT_SECRET_KEY")
app.config["JWT_ACCESS_TOKEN_EXPIRES"] = timedelta(hours=24)
jwt = JWTManager(app)
BACKEND_BASE = "https://deepthoughtai-pl-ai-backend.hf.space"
HF_TOKEN = os.environ.get("HF_TOKEN")
def _backend_headers() -> dict:
if HF_TOKEN is None:
return {}
return {"Authorization": f"Bearer {HF_TOKEN}"}
# ============================================================
# LOGIN ENDPOINT
# ============================================================
@app.post("/login")
def login():
data = request.get_json(force=True) or {}
username = (data.get("username") or "").strip()
password = (data.get("password") or "").strip()
if not username or not password:
return jsonify({"ok": False, "error": "Missing credentials"}), 400
if HF_TOKEN is None:
return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
try:
resp = requests.post(
f"{BACKEND_BASE}/auth/login",
json={"username": username, "password": password},
headers=_backend_headers(),
timeout=20,
)
except Exception as e:
return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
try:
backend_json = resp.json()
except ValueError:
return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
if not resp.ok or not backend_json.get("ok"):
return (
jsonify({"ok": False, "error": backend_json.get("error") or "Login failed"}),
resp.status_code,
)
access_token = create_access_token(identity=username)
return jsonify({"ok": True, "token": access_token}), 200
# ============================================================
# REGISTER ENDPOINT (ADMIN ONLY)
# ============================================================
@app.post("/register")
@jwt_required()
def register():
identity = (get_jwt_identity() or "").strip()
if HF_TOKEN is None:
return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
try:
data = request.get_json(force=True) or {}
except Exception:
return jsonify({"ok": False, "error": "Invalid JSON"}), 400
username = (data.get("username") or "").strip()
password = (data.get("password") or "").strip()
overwrite = bool(data.get("overwrite", False))
make_admin = bool(data.get("is_admin", False))
if not username or not password:
return jsonify({"ok": False, "error": "Missing credentials"}), 400
try:
resp = requests.post(
f"{BACKEND_BASE}/auth/register",
json={
"admin_username": identity,
"username": username,
"password": password,
"overwrite": overwrite,
"is_admin": make_admin,
},
headers=_backend_headers(),
timeout=20,
)
except Exception as e:
return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
try:
backend_json = resp.json()
except ValueError:
return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
if not resp.ok or not backend_json.get("ok"):
return (
jsonify({"ok": False, "error": backend_json.get("error") or "Register failed"}),
resp.status_code,
)
return jsonify({"ok": True, "username": backend_json.get("username") or username}), 200
# ============================================================
# CURRENT USER INFO (JWT REQUIRED)
# ============================================================
@app.get("/me")
@jwt_required()
def me():
identity = (get_jwt_identity() or "").strip()
if HF_TOKEN is None:
return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
try:
resp = requests.get(
f"{BACKEND_BASE}/auth/me",
params={"username": identity},
headers=_backend_headers(),
timeout=20,
)
except Exception as e:
return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
try:
backend_json = resp.json()
except ValueError:
return jsonify({"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}), 502
if not resp.ok or not backend_json.get("ok"):
return (
jsonify({"ok": False, "error": backend_json.get("error") or "Failed to fetch user info"}),
resp.status_code,
)
return jsonify({"ok": True, "username": identity, "is_admin": bool(backend_json.get("is_admin"))}), 200
# ============================================================
# NON-STREAMING CHAT (JSON → JSON)
# ============================================================
@app.route("/chat", methods=["POST"])
@jwt_required()
def proxy_chat():
if HF_TOKEN is None:
return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
try:
payload = request.get_json(force=True) or {}
except Exception:
return jsonify({"ok": False, "error": "Invalid JSON"}), 400
try:
resp = requests.post(
f"{BACKEND_BASE}/chat",
json=payload,
headers={"Authorization": f"Bearer {HF_TOKEN}"},
timeout=60,
)
except Exception as e:
return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
try:
data = resp.json()
except ValueError:
return jsonify(
{"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}
), 502
return jsonify(data), resp.status_code
# ============================================================
# STREAMING CHAT (TEXT STREAM → TEXT STREAM)
# ============================================================
@app.route("/chat/stream", methods=["POST"])
@jwt_required()
def proxy_chat_stream():
if HF_TOKEN is None:
return Response("HF_TOKEN not configured", status=500)
try:
payload = request.get_json(force=True) or {}
except Exception:
return Response("Invalid JSON", status=400)
def generate():
with requests.post(
f"{BACKEND_BASE}/chat/stream",
json=payload,
headers={"Authorization": f"Bearer {HF_TOKEN}"},
stream=True,
timeout=300,
) as r:
if r.status_code != 200:
# Surface backend error as a single line
yield f"[Backend error {r.status_code}]"
return
# 🔥 IMPORTANT: use iter_content so we DON'T strip newlines
for chunk in r.iter_content(chunk_size=1024):
if chunk:
yield chunk.decode("utf-8")
return Response(stream_with_context(generate()),
mimetype="text/plain")
# ============================================================
# RAW PROLOG QUERY PROXY
# ============================================================
@app.route("/prolog/query", methods=["POST"])
@jwt_required()
def proxy_prolog_query():
if HF_TOKEN is None:
return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
try:
payload = request.get_json(force=True) or {}
except Exception:
return jsonify({"ok": False, "error": "Invalid JSON"}), 400
try:
resp = requests.post(
f"{BACKEND_BASE}/prolog/query",
json=payload,
headers={"Authorization": f"Bearer {HF_TOKEN}"},
timeout=60,
)
except Exception as e:
return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
try:
data = resp.json()
except ValueError:
return jsonify(
{"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}
), 502
return jsonify(data), resp.status_code
# ============================================================
# PROLOG UPLOAD PROXY
# ============================================================
@app.route("/prolog/upload", methods=["POST"])
@jwt_required()
def proxy_prolog_upload():
if HF_TOKEN is None:
return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
try:
payload = request.get_json(force=True) or {}
except Exception:
return jsonify({"ok": False, "error": "Invalid JSON"}), 400
try:
resp = requests.post(
f"{BACKEND_BASE}/prolog/upload",
json=payload,
headers={"Authorization": f"Bearer {HF_TOKEN}"},
timeout=60,
)
except Exception as e:
return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
try:
data = resp.json()
except ValueError:
return jsonify(
{"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}
), 502
return jsonify(data), resp.status_code
# ============================================================
# KB METADATA PROXY
# ============================================================
@app.route("/prolog/metadata", methods=["GET"])
@jwt_required()
def proxy_kb_metadata():
if HF_TOKEN is None:
return jsonify({"ok": False, "error": "HF_TOKEN not configured"}), 500
try:
resp = requests.get(
f"{BACKEND_BASE}/prolog/metadata",
headers={"Authorization": f"Bearer {HF_TOKEN}"},
timeout=30,
)
except Exception as e:
return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502
try:
data = resp.json()
except ValueError:
return jsonify(
{"ok": False, "error": f"Backend returned non-JSON: {resp.text[:200]}"}
), 502
return jsonify(data), resp.status_code
# ============================================================
# HEALTH CHECK
# ============================================================
@app.get("/")
def health():
return "Gateway OK", 200
# ============================================================
# MAIN
# ============================================================
if __name__ == "__main__":
port = int(os.environ.get("PORT", 7860))
app.run(host="0.0.0.0", port=port)
|