commit a3cfac6d54b3bff05cc0b12ebb2efd76e712408d Author: reform Date: Fri Nov 6 11:27:49 2026 +0300 souz.ai: TG-OAuth mass registration + pool shim (100 RUB accounts) diff --git a/README.md b/README.md new file mode 100644 index 0000000..19213c5 --- /dev/null +++ b/README.md @@ -0,0 +1,60 @@ +# souz-autoreg + +Массовая регистрация [souz.ai](https://souz.ai) через Telegram-OAuth + OpenAI-совместимый пул-шим +для ротации ключей (100 ₽welcome-баланс на аккаунт). + +## Как работает регистрация + +1. `GET https://souz.ai/` — получить cookies (`souz_vid`, `souz_visit`). +2. `GET /v1/auth/telegram/start?next=%2Foverview` → `{"code": ""}`. +3. Telegram-бот `@souz_ai_bot`: `StartBotRequest(bot="souz_ai_bot", start_param=code)` из Telethon + (1 TG-аккаунт = 1 аккаунт souz). +4. `GET /v1/auth/telegram/poll?code=` — статус `done` после ~2-5 с. +5. `GET /v1/auth/telegram/complete?code=` — ставит cookie `client_session`. +6. `GET /v1/balance` → `available_micro: 100000000` (100 ₽) на свежих аккаунтах. +7. `POST /v1/keys {"name":"main"}` → `{"key":"sk_abc...xyz"}`. + +**Важно:** ключ в ответе выглядит маскированным (`sk_ae2...c8fc`), но это и есть полный ключ — +его надо слать как есть в `Authorization: Bearer`. Cookie-сессия для `/v1/chat/completions` +НЕ подходит (401 invalid_api_key). + +## Скрипты + +| Скрипт | Назначение | +|---|---| +| `scripts/souz_reg.py` | одна регистрация: visit → start → bot → poll → complete → ключ | +| `scripts/souz_par.py` | пачка потоков, `python3 souz_par.py LIMIT WORKERS` | +| `scripts/souz_shim.py` | пул-шим `:48023`: ротация ключей, 401/402 → dead, 403 `account_blocked` → dead, прочие 403 → кулдаун, SSE passthrough | +| `scripts/sync_keys.py` | банк → `keys.jsonl` (только аккаунты с балансом) | +| `scripts/souz_pump.py` | цикл: свежие сконвертированные сессии → upload → регистрация → sync | +| `scripts/model_probe.py` | проверка моделей через шим (код, латентность, ответ) | + +## Env + +- `TG_API_ID`, `TG_API_HASH` — креды Telethon (обязательно) +- `SOUZ_HOME` — рабочий каталог (по умолчанию каталог скрипта) +- `SOUZ_SESS_DIR` — каталог с `.session`-файлами + `pool_conv.json` (список путей) +- `SOUZ_KEYS` — файл ключей для шима +- `SOCKS/HTTP` прокси не обязательны: souz.ai отвечает не со всех IP — если属地 таймаут, + запускайте регистратор с сервера, который видит сайт + +## Замеры (2026-11-05/06) + +- Скорость: ~6-8 с/аккаунт, 4 воркера ≈ 30 акк/мин; `start` лимитит 429 → ретрай 8-32 с +- Бонус 100 ₽: ~2.8% аккаунтов (42 из 1509), остальным `available_micro: 0` +- Антифрод: `403 account_blocked` на части аккаунтов после ~60-90 регистрация с одного IP +- Модели 23/23 chat-моделей ответили 200 через пул (gpt-6.1-sol 2-6 с, claude-opus-5.5 3 с, + grok-4.7 до 18 с); `gpt-image-2.5` только через `/v1/images/generations` +- Цены (₽/1M, вход/выход): gpt-6.1-sol 146/732, claude-opus-5.5 363/1817, deepseek-v4.1-flash 3.2/59 + +## Грабли + +- `max_tokens` меньше ~32 → `400 invalid_request` («the request was rejected») — не признак мёртвого ключа +- `402 insufficient_balance` — бонус сняли/не был выдан +- Бонус отзывают постфактум: проверяйте живость ключа запросом перед использованием +- Сайт закрыт для части датацентр-подсетей (TLS timeout) — нужен egress, с которого `GET /v1/status` даёт 200 +- Телеграм-сессии со старой схемой не читаются Telethon напрямую — нужна конвертация auth_key + +## Лицензия + +AGPL-3.0 \ No newline at end of file diff --git a/scripts/__pycache__/model_probe.cpython-311.pyc b/scripts/__pycache__/model_probe.cpython-311.pyc new file mode 100644 index 0000000..a4d5fa3 Binary files /dev/null and b/scripts/__pycache__/model_probe.cpython-311.pyc differ diff --git a/scripts/__pycache__/souz_par.cpython-311.pyc b/scripts/__pycache__/souz_par.cpython-311.pyc new file mode 100644 index 0000000..43955ca Binary files /dev/null and b/scripts/__pycache__/souz_par.cpython-311.pyc differ diff --git a/scripts/__pycache__/souz_pump.cpython-311.pyc b/scripts/__pycache__/souz_pump.cpython-311.pyc new file mode 100644 index 0000000..40bf90e Binary files /dev/null and b/scripts/__pycache__/souz_pump.cpython-311.pyc differ diff --git a/scripts/__pycache__/souz_reg.cpython-311.pyc b/scripts/__pycache__/souz_reg.cpython-311.pyc new file mode 100644 index 0000000..72431d0 Binary files /dev/null and b/scripts/__pycache__/souz_reg.cpython-311.pyc differ diff --git a/scripts/__pycache__/souz_shim.cpython-311.pyc b/scripts/__pycache__/souz_shim.cpython-311.pyc new file mode 100644 index 0000000..9bc3fb5 Binary files /dev/null and b/scripts/__pycache__/souz_shim.cpython-311.pyc differ diff --git a/scripts/__pycache__/sync_keys.cpython-311.pyc b/scripts/__pycache__/sync_keys.cpython-311.pyc new file mode 100644 index 0000000..ad6f773 Binary files /dev/null and b/scripts/__pycache__/sync_keys.cpython-311.pyc differ diff --git a/scripts/model_probe.py b/scripts/model_probe.py new file mode 100644 index 0000000..69cfb15 --- /dev/null +++ b/scripts/model_probe.py @@ -0,0 +1,33 @@ +import json, time, urllib.request, urllib.error + +MODELS = ["gpt-6.1-sol", "gpt-6-sol", "gpt-6-astra", "gpt-6-luna", "claude-opus-5.5", "claude-opus-5", + "claude-sonnet-5.5", "claude-haiku-5.5", "claude-fable-5.1", "kimi-k3", "glm-5.3", + "glm-5.3-flash", "deepseek-v4.1-flash", "qwen3.8-max", "qwen3.8-27b", "grok-4.7", + "gemini-3.8-flash", "gemini-4-argon", "minimax-m3", "gpt-5.6-sol", "gpt-5.6-terra", + "gpt-5.6-luna", "kimi-k3.1-pro", "gpt-image-2.5"] +OUT = [] + + +def call(model, prompt="Столица Франции — одним словом", mt=64, timeout=100): + body = json.dumps({"model": model, "messages": [{"role": "user", "content": prompt}], "max_tokens": mt}).encode() + h = {"Content-Type": "application/json", "User-Agent": "Mozilla/5.0 Chrome/156"} + t0 = time.time() + try: + r = urllib.request.urlopen(urllib.request.Request("http://127.0.0.1:48023/v1/chat/completions", + data=body, headers=h), timeout=timeout) + d = json.loads(r.read()) + ch = (d.get("choices") or [{}])[0] + txt = (ch.get("message") or {}).get("content") or "" + return 200, round(time.time() - t0, 1), (txt or "")[:60].replace("\n", " ") + except urllib.error.HTTPError as e: + return e.code, round(time.time() - t0, 1), e.read()[:90].decode("utf-8", "replace") + except Exception as e: + return -1, round(time.time() - t0, 1), type(e).__name__ + + +for m in MODELS: + code, dt, txt = call(m) + OUT.append({"model": m, "code": code, "sec": dt, "sample": txt}) + print("%-22s %-4s %5.1fs %s" % (m, code, dt, txt[:70]), flush=True) +json.dump(OUT, open("/root/souz/model_probe.json", "w"), ensure_ascii=False, indent=1) +print("saved") \ No newline at end of file diff --git a/scripts/souz_par.py b/scripts/souz_par.py new file mode 100644 index 0000000..b8e33f4 --- /dev/null +++ b/scripts/souz_par.py @@ -0,0 +1,71 @@ +"""Parallel souz wave: N worker threads, each registers its own TG session.""" +import importlib.util, json, os, queue, sys, threading, time + +HERE = os.environ.get("SOUZ_HOME", os.environ.get("SOUZ_HOME", os.path.dirname(os.path.abspath(__file__)))) +spec = importlib.util.spec_from_file_location("sw", os.path.join(HERE, "souz_wave.py")) +sw = importlib.util.module_from_spec(spec) +spec.loader.exec_module(sw) + +BANK = os.environ.get("SOUZ_BANK", os.path.join(HERE, "souz_bank.jsonl")) +LOCK = threading.Lock() + + +def tried(): + out = set() + if os.path.exists(BANK): + for line in open(BANK, encoding="utf-8"): + try: + out.add(json.loads(line).get("session")) + except Exception: + pass + return out + + +def main(): + limit = int(sys.argv[1]) if len(sys.argv) > 1 else 100 + workers = int(sys.argv[2]) if len(sys.argv) > 2 else 6 + done = tried() + all_s = sw.load_sessions() + todo = [s for s in all_s if s not in done][:limit] + q = queue.Queue() + for s in todo: + q.put(s) + print("todo=%d workers=%d" % (len(todo), workers), flush=True) + counters = {"ok": 0, "fail": 0, "bonus": 0} + + def worker(idx): + while True: + try: + sp = q.get_nowait() + except queue.Empty: + return + t0 = time.time() + try: + res = sw.register(sp) + except Exception as e: + res = {"session": sp, "err": "exc:%s" % type(e).__name__} + res["elapsed"] = round(time.time() - t0, 1) + with LOCK: + with open(BANK, "a", encoding="utf-8") as f: + f.write(json.dumps(res, ensure_ascii=False) + "\n") + if res.get("ok"): + counters["ok"] += 1 + bal = (res.get("balance") or {}).get("available_micro") or 0 + if bal > 0: + counters["bonus"] += 1 + print("OK b=%s %s %.0fs [ok=%d bonus=%d]" % (bal, os.path.basename(sp)[:26], + res["elapsed"], counters["ok"], counters["bonus"]), flush=True) + else: + counters["fail"] += 1 + print("FAIL %s %s" % (os.path.basename(sp)[:26], res.get("err")), flush=True) + + ths = [threading.Thread(target=worker, args=(i,), daemon=True) for i in range(workers)] + for t in ths: + t.start() + for t in ths: + t.join() + print("DONE ok=%d fail=%d bonus=%d" % (counters["ok"], counters["fail"], counters["bonus"]), flush=True) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/souz_pump.py b/scripts/souz_pump.py new file mode 100644 index 0000000..f2e4fe7 --- /dev/null +++ b/scripts/souz_pump.py @@ -0,0 +1,59 @@ +"""souz_pump: pick converted sessions -> upload to prod -> register -> sync keys. One cycle per call.""" +import json, os, subprocess, sys, tarfile, time + +BASE = r"C:\Users\User\tmp\tg_chat_grow" +OKF = os.path.join(BASE, "conv_sql_ok.json") +DONE = os.path.join(BASE, "souz_uploaded.txt") +TGZ = r"C:\Users\User\tmp\souz\pump.tgz" +KEY = r"C:\Users\User\.ssh\id_ed25519" +HOST = os.environ.get("SOUZ_SSH", "root@2.27.98.196") +SSH = ["ssh", "-o", "StrictHostKeyChecking=no", "-o", "ConnectTimeout=20", "-i", KEY, HOST] +SCP = ["scp", "-o", "StrictHostKeyChecking=no", "-i", KEY] + +ENV = "TG_API_ID=23926822 TG_API_HASH=f383e16e2f55bc0857291510fd513002" + + +def log(*a): + print(time.strftime("%H:%M:%S"), *a, flush=True) + + +def main(): + batch = int(sys.argv[1]) if len(sys.argv) > 1 else 250 + if not os.path.exists(OKF): + log("no conv ok file yet") + return + ok = json.load(open(OKF, encoding="utf-8")) + done = set() + if os.path.exists(DONE): + done = set(x.strip() for x in open(DONE, encoding="utf-8") if x.strip()) + new = [p for p in ok if p not in done and os.path.exists(p)][:batch] + log("converted=%d uploaded=%d new=%d" % (len(ok), len(done), len(new))) + if not new: + return + if os.path.exists(TGZ): + os.remove(TGZ) + t = tarfile.open(TGZ, "w:gz") + n = 0 + for p in new: + t.add(p, arcname=os.path.basename(p)) + n += 1 + t.close() + size = os.path.getsize(TGZ) + log("packed %d (%.0f MB)" % (n, size / 1e6)) + r = subprocess.run(SCP + [TGZ, HOST + ":/root/souz/pump.tgz"], capture_output=True, text=True) + if r.returncode != 0: + log("scp fail", r.stderr[-200:]) + return + cmd = ("cd /root/souz && tar xzf pump.tgz -C sessions/ && cd sessions && ls *.session | python3 -c " + "'import sys,json;print(json.dumps([\"/root/souz/sessions/\"+l.strip() for l in sys.stdin]))' > pool_conv.json && " + "cd /root/souz && %s python3 souz_par.py %d 4 | tail -2 && python3 sync_keys.py && curl -s -m 5 http://127.0.0.1:48023/status" % (ENV, n + 30)) + r = subprocess.run(SSH + [cmd], capture_output=True, text=True, timeout=3600) + log("remote:", (r.stdout or "").strip()[-300:]) + if r.returncode == 0 and "DONE" in (r.stdout or ""): + with open(DONE, "a", encoding="utf-8") as f: + for p in new: + f.write(p + "\n") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/souz_reg.py b/scripts/souz_reg.py new file mode 100644 index 0000000..49e852c --- /dev/null +++ b/scripts/souz_reg.py @@ -0,0 +1,239 @@ +"""souz.ai mass registration over Telegram bot OAuth (1 TG account = 1 souz account, 100 RUB bonus).""" +import asyncio, json, os, random, sys, time, urllib.request, http.cookiejar + +PROXY_CFG = r"C:\Users\User\.secrets\proxy_pool.json" + + +def _load_proxies(): + try: + d = json.load(open(PROXY_CFG, encoding="utf-8")) + auth = d.get("auth") or "" + port = d.get("port") or 8888 + out = [] + for h in d.get("hosts") or []: + out.append("http://%s@%s:%s" % ((auth + "@") if auth else "", h, port)) + return out + except Exception: + return [] + + +PROXIES = _load_proxies() + + +def pick_proxy(): + if PROXIES: + return random.choice(PROXIES) + return "" + +API_ID = int(os.environ.get("TG_API_ID", 23926822)) +API_HASH = os.environ.get("TG_API_HASH", "f383e16e2f55bc0857291510fd513002") +BASE = "https://souz.ai" +UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) " + "Chrome/156.0.0.0 Safari/537.36") +HERE = os.environ.get("SOUZ_HOME", os.path.dirname(os.path.abspath(__file__))) +BANK = os.environ.get("SOUZ_BANK", os.path.join(HERE, "souz_bank.jsonl")) +DEAD = os.path.join(HERE, "souz_dead.txt") +LOG = open(os.path.join(HERE, "souz_wave.log"), "a", encoding="utf-8", buffering=1) + + +def log(*a): + LOG.write(time.strftime("%H:%M:%S ") + " ".join(str(x) for x in a) + "\n") + + +class Api: + def __init__(self): + self.jar = http.cookiejar.CookieJar() + self.op = None + + def _build(self, px): + self.op = urllib.request.build_opener( + urllib.request.ProxyHandler({'http': px, 'https': px}) if px else urllib.request.build_opener().handlers[0] and urllib.request.ProxyHandler({}), + urllib.request.HTTPCookieProcessor(self.jar)) + + def req(self, path, method="GET", body=None, navigate=False, follow=True, tries=3, timeout=30): + last = None + for attempt in range(tries): + px = pick_proxy() + handlers = [urllib.request.HTTPCookieProcessor(self.jar)] + if px: + handlers.append(urllib.request.ProxyHandler({'http': px, 'https': px})) + else: + handlers.append(urllib.request.ProxyHandler({})) + if not follow: + class NoRedir(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *a, **k): + return None + handlers.append(NoRedir) + op = urllib.request.build_opener(*handlers) + if navigate: + h = {"User-Agent": UA, "Accept-Language": "ru-RU,ru;q=0.9,en;q=0.8", + "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,*/*;q=0.8", + "Sec-Fetch-Site": "none", "Sec-Fetch-Mode": "navigate", "Sec-Fetch-Dest": "document", + "Sec-Fetch-User": "?1", "Upgrade-Insecure-Requests": "1"} + else: + h = {"User-Agent": UA, "Accept": "application/json, text/plain, */*", + "Accept-Language": "ru-RU,ru;q=0.9", "Referer": BASE + "/login", "Origin": BASE, + "Sec-Fetch-Site": "same-origin", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Dest": "empty"} + data = None + if body is not None: + data = json.dumps(body).encode() + h["Content-Type"] = "application/json" + try: + r = op.open(urllib.request.Request(BASE + path, data=data, headers=h, method=method), timeout=timeout) + return r.status, r.read() + except urllib.error.HTTPError as e: + return e.code, e.read() + except Exception as e: + last = type(e).__name__ + time.sleep(1.5) + return -1, str(last).encode() + + def j(self, path, method="GET", body=None, **kw): + c, b = self.req(path, method, body, **kw) + try: + return c, json.loads(b) + except Exception: + return c, {"_raw": b.decode("utf-8", "replace")[:150]} + + def cookies(self): + return {ck.name: ck.value for ck in self.jar} + + +async def tg_confirm(session_path, code): + from telethon import TelegramClient + from telethon.tl.functions.messages import StartBotRequest + cl = TelegramClient(session_path, API_ID, API_HASH, device_model="SM-G991B", system_version="13", + app_version="10.2.0", lang_code="ru", system_lang_code="ru") + try: + await cl.connect() + if not await cl.is_user_authorized(): + return {"err": "not_authorized"} + me = await cl.get_me() + await cl(StartBotRequest(bot="souz_ai_bot", peer="souz_ai_bot", start_param=code)) + await asyncio.sleep(2.5) + return {"tg_id": me.id, "tg_user": me.username, + "name": ((me.first_name or "") + " " + (me.last_name or "")).strip()} + except Exception as e: + return {"err": "tg:%s" % type(e).__name__} + finally: + try: + await cl.disconnect() + except Exception: + pass + + +def register(session_path, poll_sec=40): + api = Api() + out = {"session": session_path} + c, b = api.req("/", navigate=True) + if c != 200: + out["err"] = "visit_%s" % c + return out + st = None + for attempt in range(4): + c, st = api.j("/v1/auth/telegram/start?next=%2Foverview") + if c == 200 and isinstance(st, dict) and "code" in st: + break + if c == 429: + time.sleep(8 * (attempt + 1)) + continue + break + if not (c == 200 and isinstance(st, dict) and "code" in st): + out["err"] = "start_%s" % c + return out + code = st["code"] + info = asyncio.run(tg_confirm(session_path, code)) + out["tg"] = info + if "err" in info: + out["err"] = info["err"] + return out + status = None + for _ in range(int(poll_sec / 2)): + c, s = api.j("/v1/auth/telegram/poll?code=" + code) + if isinstance(s, dict) and s.get("status") not in (None, "pending"): + status = s.get("status") + break + time.sleep(2) + if status is None: + out["err"] = "poll_timeout" + return out + c, b = api.req("/v1/auth/telegram/complete?code=" + code, navigate=True, follow=False) + out["complete"] = c + if "client_session" not in api.cookies(): + out["err"] = "no_session_%s" % c + return out + c, me = api.j("/v1/auth/me") + out["me"] = me + c, bal = api.j("/v1/balance") + out["balance"] = bal + c, k = api.j("/v1/keys", "POST", {"name": "main"}) + out["key"] = k + out["ok"] = True + out["ts"] = int(time.time()) + return out + + +def load_sessions(): + seen, out = set(), [] + for fn in ("pool_conv.json", "pool_all2.json", "pool_live9.json"): + p = os.path.join(r"C:\Users\User\tmp\tg_chat_grow", fn) + if not os.path.exists(p): + continue + try: + data = json.load(open(p, encoding="utf-8")) + except Exception: + continue + for s in data: + if isinstance(s, dict): + s = s.get("path") or s.get("session") + if not s or s in seen: + continue + if not os.path.exists(s): + continue + seen.add(s) + out.append(s) + return out + + +def main(): + limit = int(sys.argv[1]) if len(sys.argv) > 1 else 20 + sessions = load_sessions() + done = set() + if os.path.exists(BANK): + for line in open(BANK, encoding="utf-8"): + try: + d = json.loads(line) + done.add(d.get("session")) + except Exception: + pass + log("sessions=%d done=%d limit=%d" % (len(sessions), len(done), limit)) + n = 0 + ok = 0 + for sp in sessions: + if n >= limit: + break + if sp in done: + continue + t0 = time.time() + try: + res = register(sp) + except Exception as e: + res = {"session": sp, "err": "exc:%s" % type(e).__name__} + res["elapsed"] = round(time.time() - t0, 1) + with open(BANK, "a", encoding="utf-8") as f: + f.write(json.dumps(res, ensure_ascii=False) + "\n") + n += 1 + if res.get("ok"): + ok += 1 + bal = (res.get("balance") or {}).get("available_micro") + log("OK %s tg=%s bal=%s %.0fs" % (os.path.basename(sp)[:22], res["tg"].get("tg_id"), bal, res["elapsed"])) + else: + log("FAIL %s %s" % (os.path.basename(sp)[:22], res.get("err"))) + if res.get("err") in ("not_authorized", "tg:AuthKeyUnregistered", "tg:AuthKeyDuplicated"): + with open(DEAD, "a", encoding="utf-8") as f: + f.write(sp + "\n") + log("batch done ok=%d/%d" % (ok, n)) + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/souz_shim.py b/scripts/souz_shim.py new file mode 100644 index 0000000..c903cec --- /dev/null +++ b/scripts/souz_shim.py @@ -0,0 +1,191 @@ +#!/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() \ No newline at end of file diff --git a/scripts/sync_keys.py b/scripts/sync_keys.py new file mode 100644 index 0000000..3943767 --- /dev/null +++ b/scripts/sync_keys.py @@ -0,0 +1,22 @@ +import json, os, sys + +src = os.environ.get("SOUZ_BANK", "souz_bank.jsonl") +dst = os.environ.get("SOUZ_KEYS", "keys.jsonl") +seen, out = set(), [] +for line in open(src, encoding="utf-8"): + try: + r = json.loads(line) + except Exception: + continue + if not r.get("ok"): + continue + bal = (r.get("balance") or {}).get("available_micro") or 0 + k = (r.get("key") or {}).get("key") or "" + if bal <= 0 or not k or k in seen: + continue + seen.add(k) + out.append({"key": k, "user": (r.get("tg") or {}).get("tg_id"), "bal": bal}) +lines = [json.dumps(x, ensure_ascii=False) for x in out] +NL = chr(10) +open(dst, "w", encoding="utf-8").write(NL.join(lines) + NL) +print("synced", len(out))