File size: 6,437 Bytes
ee67bad
 
853127f
d102aa8
f0b72ce
d102aa8
 
6614244
62e9fe3
 
d102aa8
3b0b8ee
 
 
 
 
 
 
d102aa8
853127f
d102aa8
62e9fe3
 
ee67bad
62e9fe3
 
 
 
 
 
 
ee67bad
62e9fe3
 
ee67bad
62e9fe3
ee67bad
62e9fe3
 
 
 
 
 
ee67bad
0f96b62
79b8999
3b0b8ee
 
ee67bad
d102aa8
 
068a29f
 
 
 
 
3b0b8ee
f0b72ce
 
ee67bad
f0b72ce
c852da2
 
 
 
 
 
 
 
 
068a29f
 
 
 
 
 
e00400b
068a29f
 
e00400b
068a29f
 
 
ee67bad
068a29f
 
ee67bad
c852da2
 
 
3b0b8ee
d102aa8
e00400b
ee67bad
e00400b
 
 
 
 
ee67bad
e00400b
 
 
068a29f
e00400b
 
 
 
068a29f
 
 
 
 
 
 
 
 
 
 
 
 
ee67bad
068a29f
 
 
 
ee67bad
068a29f
 
e00400b
 
f019318
ee67bad
f019318
 
 
 
 
068a29f
 
 
 
 
 
 
ee67bad
068a29f
 
 
 
ee67bad
068a29f
 
f019318
 
f0b72ce
ee67bad
f0b72ce
 
 
 
 
 
 
 
 
 
 
 
 
ee67bad
f0b72ce
 
 
 
 
 
060dbbd
f0b72ce
 
 
060dbbd
 
 
 
 
 
f0b72ce
 
 
ee67bad
f0b72ce
d102aa8
 
 
 
 
 
fa5fbe4
853127f
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
# app.py - Prolog AI Gateway
# JWT authentication + proxy to backend for chat/stream

import os
from flask import Flask, request, jsonify, Response, stream_with_context
from flask_cors import CORS
import requests
from datetime import timedelta
from werkzeug.exceptions import HTTPException
import uuid

from flask_jwt_extended import (
    JWTManager,
    create_access_token,
    jwt_required,
    get_jwt_identity,
)

app = Flask(__name__)
CORS(app)


@app.errorhandler(Exception)
def _handle_exception(e: Exception):
    request_id = uuid.uuid4().hex[:12]
    try:
        app.logger.exception("Unhandled exception request_id=%s", request_id)
    except Exception:
        pass

    status_code = 500
    message = "Internal Server Error"
    if isinstance(e, HTTPException):
        status_code = int(getattr(e, "code", 500) or 500)
        message = getattr(e, "description", message) or message

    payload: dict = {"ok": False, "error": message, "request_id": request_id}
    if (os.environ.get("EXPOSE_ERRORS") or "").strip() == "1":
        payload["type"] = type(e).__name__
        payload["details"] = str(e)

    return jsonify(payload), status_code


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 = os.environ.get("BACKEND_URL", "https://deepthoughtai-prolog-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
# ============================================================
@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

    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": "Backend returned non-JSON"}), 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 (ADMIN ONLY)
# ============================================================
@app.post("/register")
@jwt_required()
def register():
    identity = (get_jwt_identity() or "").strip()
    data = request.get_json(force=True) or {}
    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,
        )
        backend_json = resp.json()
    except Exception as e:
        return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 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
# ============================================================
@app.get("/me")
@jwt_required()
def me():
    identity = (get_jwt_identity() or "").strip()
    try:
        resp = requests.get(
            f"{BACKEND_BASE}/auth/me",
            params={"username": identity},
            headers=_backend_headers(),
            timeout=20,
        )
        backend_json = resp.json()
    except Exception as e:
        return jsonify({"ok": False, "error": f"Gateway request failed: {e}"}), 502

    if not resp.ok or not backend_json.get("ok"):
        return jsonify({"ok": False, "error": backend_json.get("error") or "Failed"}), resp.status_code

    return jsonify({"ok": True, "username": identity, "is_admin": bool(backend_json.get("is_admin"))}), 200


# ============================================================
# STREAMING CHAT (core endpoint)
# ============================================================
@app.route("/chat/stream", methods=["POST"])
@jwt_required()
def proxy_chat_stream():
    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={**_backend_headers(), "Accept": "text/plain"},
            stream=True,
            timeout=300,
        ) as r:
            if r.status_code != 200:
                yield f"[Backend error {r.status_code}]"
                return
            for chunk in r.iter_content(chunk_size=128):
                if chunk:
                    yield chunk.decode("utf-8")

    headers = {
        "Cache-Control": "no-cache",
        "X-Accel-Buffering": "no",
        "Connection": "keep-alive",
    }
    return Response(stream_with_context(generate()), mimetype="text/plain", headers=headers)


# ============================================================
# HEALTH
# ============================================================
@app.get("/")
def health():
    return "Gateway OK", 200


if __name__ == "__main__":
    port = int(os.environ.get("PORT", 7860))
    app.run(host="0.0.0.0", port=port)