File size: 5,405 Bytes
31db1d3
 
 
 
 
 
 
 
 
 
 
 
 
 
0af3440
31db1d3
0af3440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31db1d3
 
 
 
 
 
 
 
 
 
 
 
 
0af3440
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31db1d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0af3440
31db1d3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from flask import Flask, request, Response, jsonify
import requests
import threading
import time
import random
import logging
from typing import Optional

app = Flask(__name__)

# =========================
# CONFIG
# =========================
Server  = [
    "https://Techbitforge-server.hf.space"
]
HF_SERVERS = [
    "https://6lqmgwrrrn-api1.hf.space",
    "https://6lqmgwrrrn-api2.hf.space",
    "https://6lqmgwrrrn-api3.hf.space",
    "https://6lqmgwrrrn-api4.hf.space",
    "https://6lqmgwrrrn-api5.hf.space",
    "https://6lqmgwrrrn-api6.hf.space",
    "https://6lqmgwrrrn-api7.hf.space",
    "https://6lqmgwrrrn-api8.hf.space",
    "https://dokek64685-api1.hf.space",
    "https://dokek64685-api2.hf.space",
    "https://dokek64685-api3.hf.space",
    "https://dokek64685-api4.hf.space",
    "https://dokek64685-api5.hf.space",
    "https://dokek64685-api6.hf.space",
    "https://dokek64685-api7.hf.space",
    "https://dokek64685-api8.hf.space",
    "https://sayonob407-api1.hf.space",
    "https://sayonob407-api2.hf.space",
    "https://sayonob407-api3.hf.space",
    "https://sayonob407-api4.hf.space",
    "https://sayonob407-api5.hf.space",
    "https://sayonob407-api6.hf.space",
    "https://sayonob407-api7.hf.space",
    "https://sayonob407-api8.hf.space",
    "https://Shadowty491-none1.hf.space",
    "https://Shadowty491-none2.hf.space",
    "https://Shadowty491-none3.hf.space",
    "https://Shadowty491-none4.hf.space",
    "https://Shadowty491-none5.hf.space",
    "https://Shadowty491-none6.hf.space",
    "https://Shadowty491-none7.hf.space",
    "https://Shadowty491-none8.hf.space",
]

PING_INTERVAL = 120
REQUEST_TIMEOUT = 300

# =========================
# LOGGING
# =========================
logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s — %(levelname)s — %(message)s"
)
logger = logging.getLogger("proxy")


def pick_server() -> str:
    return random.choice(HF_SERVERS)


def error_response(message: str, code: int = 500):
    logger.error(message)
    return jsonify({
        "error": {
            "message": message,
            "type": "proxy_error"
        }
    }), code


# =========================
# CHAT COMPLETIONS PROXY
# =========================
@app.route("/v1/chat/completions", methods=["POST"])
def chat_completions():
    try:
        payload = request.get_json(force=True)
    except Exception:
        return error_response("Invalid JSON payload", 400)

    headers = dict(request.headers)
    headers.pop("Host", None)

    target = pick_server() + "/v1/chat/completions"
    stream = payload.get("stream", False)

    logger.info(f"Forwarding request to {target} | Stream={stream}")

    try:
        if stream:
            def generate():
                with requests.post(
                    target,
                    json=payload,
                    headers=headers,
                    stream=True,
                    timeout=REQUEST_TIMEOUT
                ) as res:
                    res.raise_for_status()
                    for line in res.iter_lines():
                        if line:
                            yield line + b"\n\n"

            return Response(
                generate(),
                mimetype="text/event-stream",
                headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"}
            )

        res = requests.post(
            target,
            json=payload,
            headers=headers,
            timeout=REQUEST_TIMEOUT
        )
        res.raise_for_status()
        return jsonify(res.json())

    except requests.exceptions.Timeout:
        return error_response("Upstream server timeout", 504)
    except requests.exceptions.ConnectionError:
        return error_response("Failed to connect to upstream server", 502)
    except Exception as e:
        return error_response(str(e), 500)


# =========================
# MODELS ROUTE
# =========================
@app.route("/models", methods=["GET"])
def models():
    url = pick_server()
    target = f"{url}/models"

    logger.info(f"Fetching models from {target}")

    try:
        res = requests.get(target, timeout=20)
        res.raise_for_status()
        return jsonify(res.json())
    except Exception as e:
        return error_response(f"Failed to fetch models: {e}", 500)


# =========================
# HEALTH CHECK
# =========================
@app.route("/", methods=["GET"])
def home():
    return jsonify({"status": "running", "service": "HF Proxy"})


# =========================
# KEEP ALIVE PINGER
# =========================
HEADERS = {"User-Agent": "HF-Proxy-KeepAliveBot"}


def keep_alive_worker():
    while True:
        logger.info("Pinging HF servers...")
        for url in HF_SERVERS + Server:
            try:
                r = requests.get(url, headers=HEADERS, timeout=8)
                logger.info(f"{url}{r.status_code}")
            except Exception as e:
                logger.warning(f"{url} → ERROR: {e}")
        time.sleep(PING_INTERVAL)


def start_background_thread():
    thread = threading.Thread(target=keep_alive_worker, daemon=True)
    thread.start()
    logger.info("Background keep-alive thread started")


# =========================
# MAIN
# =========================
if __name__ == "__main__":
    start_background_thread()
    app.run(
        host="0.0.0.0",
        port=7860,
        threaded=True,
        debug=False
    )