Spaces:
Running
Running
Download app.py from DeepThoughtAI/pl_ai_gateway: direct link, hf CLI and curl.
- Browser
- Download file 10.7 kB
-
https://huggingface.co/spaces/DeepThoughtAI/pl_ai_gateway/resolve/main/app.py
- Command line
-
hf download hf://spaces/DeepThoughtAI/pl_ai_gateway/app.py
-
curl -L -o app.py https://huggingface.co/spaces/DeepThoughtAI/pl_ai_gateway/resolve/main/app.py
10.7 kB
| # 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 | |
| # ============================================================ | |
| 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) | |
| # ============================================================ | |
| 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) | |
| # ============================================================ | |
| 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) | |
| # ============================================================ | |
| 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) | |
| # ============================================================ | |
| 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 | |
| # ============================================================ | |
| 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 | |
| # ============================================================ | |
| 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 | |
| # ============================================================ | |
| 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 | |
| # ============================================================ | |
| 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) | |