#!/usr/bin/env python3 # -*- coding: utf-8 -*- """CAMB.AI pool dashboard (stdlib only, no external CDN). Serves: GET / - single-page dashboard (dark, auto-refresh 30s) GET /api/stats - JSON: pool totals, per-account credits, shim health GET /api/refresh - force a credit re-check (async, returns immediately) GET /health - liveness Sources: bank : camb_bank.jsonl {email,password,team_id,api_key,credits,...} shim : http://127.0.0.1:8822/health camb : GET https://client.camb.ai/payments/credits/team/ (bearer = api_key) """ import json import os import sys import threading import time import urllib.error import urllib.request import traceback from concurrent.futures import ThreadPoolExecutor from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer HERE = os.path.dirname(os.path.abspath(__file__)) BANK = os.environ.get("CAMB_BANK", os.path.join(HERE, "camb_bank.jsonl")) STATS = os.environ.get("CAMB_STATS", os.path.join(HERE, "camb_stats.json")) SHIM = os.environ.get("CAMB_SHIM", "http://127.0.0.1:8822") PORT = int(os.environ.get("CAMB_DASH_PORT", "8823")) REFRESH_EVERY = int(os.environ.get("CAMB_REFRESH_SEC", "300")) # argv override (env vars do not always survive the Windows/MSYS shell): # dashboard.py --port 8823 --bank /opt/camb-shim/camb_bank.jsonl --shim http://127.0.0.1:8822 _argv = sys.argv[1:] for i, a in enumerate(_argv): if a in ("--port", "--bank", "--stats", "--shim", "--refresh") and i + 1 < len(_argv): v = _argv[i + 1] if a == "--port": PORT = int(v) elif a == "--bank": BANK = v elif a == "--stats": STATS = v elif a == "--shim": SHIM = v elif a == "--refresh": REFRESH_EVERY = int(v) _lock = threading.Lock() _cache = {"ts": 0, "accounts": [], "totals": {}} _refreshing = False def read_bank(): dec = json.JSONDecoder() rows = [] if not os.path.exists(BANK): return rows with open(BANK, encoding="utf-8", errors="replace") as fh: for line in fh: s = line.strip() i = 0 while i < len(s): while i < len(s) and s[i] in " \t\r": i += 1 if i >= len(s): break try: obj, nxt = dec.raw_decode(s, i) except ValueError: break if isinstance(obj, dict): rows.append(obj) i = nxt return rows def unique_accounts(rows): seen = set() out = [] for r in rows: key = str(r.get("team_id") or r.get("email") or "").strip() if not key or key in seen: continue seen.add(key) out.append({ "email": str(r.get("email") or ""), "team_id": str(r.get("team_id") or ""), "api_key": str(r.get("api_key") or ""), "credits": r.get("credits"), "ts": r.get("ts"), }) return out def check_key(acc, timeout=20): """Key liveness without spending credits: GET /apis/list-voices (x-api-key). Returns True alive / False dead. There is no credit endpoint for API keys (`/payments/credits/team/` needs a user JWT -> 401), so per-account credit numbers come from the bank (`credits` field) and from real TTS spends (`tts_credits`). """ if not acc.get("api_key"): return False req = urllib.request.Request("https://client.camb.ai/apis/list-voices", headers={ "x-api-key": acc["api_key"], "Accept": "application/json", "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/141.0", }) try: with urllib.request.urlopen(req, timeout=timeout) as r: return r.status == 200 except urllib.error.HTTPError: return False except (urllib.error.URLError, OSError): return False def shim_health(): try: with urllib.request.urlopen(SHIM + "/health", timeout=6) as r: return json.loads(r.read() or b"{}") except Exception: # noqa: BLE001 - health must never break the page return {"status": "down"} def refresh_all(): global _refreshing with _lock: if _refreshing: return _refreshing = True try: rows = read_bank() accounts = unique_accounts(rows) keys = [a for a in accounts if a.get("api_key")] alive = 0 with ThreadPoolExecutor(max_workers=8) as pool: verdicts = list(pool.map(check_key, keys)) for acc, ok in zip(keys, verdicts): acc["alive"] = ok if ok: alive += 1 acc["key_tail"] = "..." + acc["api_key"][-6:] acc.pop("api_key", None) for acc in accounts: acc.setdefault("alive", False) acc.setdefault("key_tail", "") capacity = len(keys) * 5000 spent = 0.0 for r in rows: try: spent += float(r.get("tts_credits") or 0) except (TypeError, ValueError): spent = spent totals = { "records": len(rows), "accounts": len(accounts), "keys": len(keys), "alive": alive, "dead": len(keys) - alive, "credits_left": round(capacity - spent, 2), "credits_capacity": capacity, "spent": round(spent, 2), "tts_phrases": int((capacity - spent) / 3.0938) if capacity else 0, "dubs": int((capacity - spent) / 550) if capacity else 0, "usd_value": round((capacity - spent) * 0.0005, 2), "shim": shim_health(), "updated": int(time.time()), } with _lock: _cache["ts"] = int(time.time()) _cache["accounts"] = accounts _cache["totals"] = totals with open(STATS, "w", encoding="utf-8") as fh: json.dump(_cache, fh, ensure_ascii=False) print("refresh done: %d accounts, %d keys alive, %.0f credits" % ( len(accounts), alive, capacity - spent), flush=True) except Exception: # noqa: BLE001 - keep the server alive, surface the error traceback.print_exc() finally: with _lock: _refreshing = False def boot(): try: with open(STATS, encoding="utf-8") as fh: data = json.load(fh) with _lock: _cache.update(data) except (OSError, ValueError): threading.Thread(target=refresh_all, daemon=True).start() if time.time() - _cache.get("ts", 0) > REFRESH_EVERY: threading.Thread(target=refresh_all, daemon=True).start() threading.Thread(target=loop, daemon=True).start() def loop(): while True: time.sleep(REFRESH_EVERY) refresh_all() PAGE = """ CAMB pool

CAMB.AI pool

loading…
#Аккаунтteam_idКредитыКлючСтатус
загрузка…
""" class H(BaseHTTPRequestHandler): protocol_version = "HTTP/1.1" def log_message(self, fmt, *a): print("%s %s" % (time.strftime("%H:%M:%S"), fmt % a), flush=True) def _send(self, code, body, ctype): raw = body.encode() if isinstance(body, str) else body self.send_response(code) self.send_header("Content-Type", ctype) self.send_header("Content-Length", str(len(raw))) self.send_header("Cache-Control", "no-store") self.end_headers() self.wfile.write(raw) def do_GET(self): p = self.path.split("?")[0] if p == "/": return self._send(200, PAGE, "text/html; charset=utf-8") if p == "/api/stats": with _lock: snap = {"totals": _cache["totals"], "accounts": _cache["accounts"], "ts": _cache["ts"]} return self._send(200, json.dumps(snap, ensure_ascii=False), "application/json; charset=utf-8") if p == "/api/refresh": threading.Thread(target=refresh_all, daemon=True).start() return self._send(200, json.dumps({"started": True}), "application/json") if p == "/health": with _lock: return self._send(200, json.dumps({"status": "ok", "accounts": len(_cache["accounts"]), "updated": _cache["ts"]}), "application/json") return self._send(404, json.dumps({"error": "not found"}), "application/json") def main(): boot() print("camb-dash on :%d bank=%s shim=%s" % (PORT, BANK, SHIM), flush=True) ThreadingHTTPServer(("0.0.0.0", PORT), H).serve_forever() if __name__ == "__main__": main()