191 lines
7.4 KiB
Python
191 lines
7.4 KiB
Python
#!/usr/bin/env python3
|
|
"""souz-shim: OpenAI-compatible pool over souz.ai accounts (100 RUB / account)."""
|
|
import json, os, sys, threading, time, urllib.request, urllib.error
|
|
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
|
|
|
UPSTREAM = "https://souz.ai"
|
|
KEYS_FILE = os.environ.get("SOUZ_KEYS", "keys.jsonl")
|
|
STATE = os.environ.get("SOUZ_STATE", "state.json")
|
|
PORT = int(os.environ.get("SOUZ_PORT", "48023"))
|
|
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/156.0.0.0 Safari/537.36"
|
|
|
|
lock = threading.Lock()
|
|
keys = [] # [{"key":..., "user":...}]
|
|
dead = {} # key -> ts
|
|
cursor = [0]
|
|
stats = {"ok": 0, "err": 0, "dead": 0}
|
|
|
|
|
|
def load_keys():
|
|
global keys
|
|
out = []
|
|
try:
|
|
for line in open(KEYS_FILE, encoding="utf-8"):
|
|
line = line.strip()
|
|
if not line:
|
|
continue
|
|
try:
|
|
d = json.loads(line)
|
|
except Exception:
|
|
continue
|
|
k = d.get("key") or ""
|
|
if k and k not in [x["key"] for x in out]:
|
|
out.append({"key": k, "user": d.get("user") or ""})
|
|
except Exception as e:
|
|
print("keys load error", e, flush=True)
|
|
keys = out
|
|
return len(keys)
|
|
|
|
|
|
def alive_keys():
|
|
now = time.time()
|
|
return [k for k in keys if now - dead.get(k["key"], 0) > 1800]
|
|
|
|
|
|
def call(path, body, key, stream=False, timeout=180):
|
|
h = {"Content-Type": "application/json", "Authorization": "Bearer " + key, "User-Agent": UA,
|
|
"Origin": UPSTREAM, "Referer": UPSTREAM + "/dashboard",
|
|
"Accept": "text/event-stream" if stream else "application/json"}
|
|
req = urllib.request.Request(UPSTREAM + path, data=body, headers=h, method="POST")
|
|
return urllib.request.urlopen(req, timeout=timeout)
|
|
|
|
|
|
class H(BaseHTTPRequestHandler):
|
|
protocol_version = "HTTP/1.1"
|
|
|
|
def log_message(self, *a):
|
|
pass
|
|
|
|
def _json(self, code, obj):
|
|
b = json.dumps(obj, ensure_ascii=False).encode()
|
|
self.send_response(code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(b)))
|
|
self.end_headers()
|
|
self.wfile.write(b)
|
|
|
|
def do_GET(self):
|
|
if self.path.startswith("/status"):
|
|
return self._json(200, {"keys": len(keys), "alive": len(alive_keys()), "dead": len(dead),
|
|
"stats": stats, "upstream": UPSTREAM})
|
|
if self.path.startswith("/v1/models"):
|
|
try:
|
|
r = urllib.request.urlopen(urllib.request.Request(UPSTREAM + "/v1/models",
|
|
headers={"User-Agent": UA}), timeout=30)
|
|
b = r.read()
|
|
self.send_response(200)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(b)))
|
|
self.end_headers()
|
|
self.wfile.write(b)
|
|
return
|
|
except Exception as e:
|
|
return self._json(502, {"error": str(e)})
|
|
load_keys()
|
|
return self._json(200, {"status": "ok", "keys": len(keys)})
|
|
|
|
def do_POST(self):
|
|
n = int(self.headers.get("Content-Length") or 0)
|
|
body = self.rfile.read(n)
|
|
try:
|
|
req = json.loads(body or b"{}")
|
|
except Exception:
|
|
return self._json(400, {"error": {"message": "bad json"}})
|
|
stream = bool(req.get("stream"))
|
|
path = self.path
|
|
tries = min(6, max(1, len(alive_keys())))
|
|
last = None
|
|
for i in range(tries):
|
|
with lock:
|
|
pool = alive_keys()
|
|
if not pool:
|
|
load_keys()
|
|
pool = alive_keys()
|
|
if not pool:
|
|
return self._json(429, {"error": {"message": "no souz keys alive", "type": "pool_empty"}})
|
|
k = pool[cursor[0] % len(pool)]
|
|
cursor[0] += 1
|
|
try:
|
|
r = call(path, body, k["key"], stream=stream)
|
|
if stream:
|
|
self.send_response(r.status)
|
|
self.send_header("Content-Type", r.headers.get("Content-Type", "text/event-stream"))
|
|
self.send_header("Cache-Control", "no-cache")
|
|
self.send_header("Transfer-Encoding", "chunked")
|
|
self.end_headers()
|
|
while True:
|
|
chunk = r.read(2048)
|
|
if not chunk:
|
|
break
|
|
self.wfile.write(b"%x\r\n%s\r\n" % (len(chunk), chunk))
|
|
self.wfile.flush()
|
|
self.wfile.write(b"0\r\n\r\n")
|
|
self.wfile.flush()
|
|
else:
|
|
data = r.read()
|
|
self.send_response(r.status)
|
|
self.send_header("Content-Type", r.headers.get("Content-Type", "application/json"))
|
|
self.send_header("Content-Length", str(len(data)))
|
|
self.end_headers()
|
|
self.wfile.write(data)
|
|
stats["ok"] += 1
|
|
return
|
|
except urllib.error.HTTPError as e:
|
|
err = e.read()
|
|
last = (e.code, err)
|
|
try:
|
|
with open(os.environ.get("SOUZ_FAILLOG", "fail.log"), "a") as fl:
|
|
fl.write("%s %s %s" % (time.time(), e.code, err[:160].decode("utf-8", "replace")) + chr(10))
|
|
except Exception:
|
|
pass
|
|
if e.code in (401, 402):
|
|
with lock:
|
|
dead[k["key"]] = time.time()
|
|
stats["dead"] += 1
|
|
continue
|
|
if e.code == 403:
|
|
body_s = err[:200].decode("utf-8", "replace")
|
|
with lock:
|
|
if "account_blocked" in body_s or "banned" in body_s:
|
|
dead[k["key"]] = time.time()
|
|
else:
|
|
dead[k["key"]] = time.time() - 1740
|
|
continue
|
|
if e.code == 429:
|
|
time.sleep(1)
|
|
continue
|
|
self.send_response(e.code)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(err)))
|
|
self.end_headers()
|
|
self.wfile.write(err)
|
|
stats["err"] += 1
|
|
return
|
|
except Exception as e:
|
|
last = (502, json.dumps({"error": str(e)}).encode())
|
|
continue
|
|
stats["err"] += 1
|
|
code, payload = last if last else (502, b'{"error":"upstream"}')
|
|
self.send_response(code if isinstance(code, int) else 502)
|
|
self.send_header("Content-Type", "application/json")
|
|
self.send_header("Content-Length", str(len(payload)))
|
|
self.end_headers()
|
|
self.wfile.write(payload)
|
|
|
|
|
|
def watch():
|
|
while True:
|
|
time.sleep(60)
|
|
try:
|
|
load_keys()
|
|
with lock:
|
|
json.dump({"dead": dead, "stats": stats, "keys": len(keys), "ts": time.time()},
|
|
open(STATE, "w"))
|
|
except Exception:
|
|
pass
|
|
|
|
|
|
if __name__ == "__main__":
|
|
print("souz-shim keys=%d port=%d" % (load_keys(), PORT), flush=True)
|
|
threading.Thread(target=watch, daemon=True).start()
|
|
ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever() |