From 6c22a4e72710bc2e5df6a9aafe6f1f436d5905e4 Mon Sep 17 00:00:00 2001 From: reform Date: Sun, 1 Nov 2026 19:27:26 +0300 Subject: [PATCH] add dashboard --- README.md | 64 +++++++++++ dashboard.py | 311 +++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 375 insertions(+) create mode 100644 dashboard.py diff --git a/README.md b/README.md index 0ed514e..6d0f56d 100644 --- a/README.md +++ b/README.md @@ -47,3 +47,67 @@ CAMB_MAIL_READER=/root/camb_code.py CAMB_KEYS=/opt/camb-shim/camb_keys.json CAMB_SHIM_PORT=8822 ``` + +## Dashboard + +`dashboard.py` — stdlib-only web panel (no CDN, no deps), dark UI, auto-refresh 30s. + +```bash +python3 dashboard.py --port 8823 --bank /opt/camb-dash/camb_bank.jsonl \ + --stats /opt/camb-dash/camb_stats.json --shim http://127.0.0.1:8822 --refresh 900 +``` + +| route | meaning | +|---|---| +| `GET /` | page: totals + per-account table | +| `GET /api/stats` | JSON snapshot (cached) | +| `GET /api/refresh` | force re-check of the pool | +| `GET /health` | liveness | + +What it shows: records / unique accounts / keys / alive / dead, credits left and capacity, +spent, TTS phrases, dubs, USD value, shim health, and a table of accounts with the +last 6 chars of each key and its liveness. + +Liveness is checked with `GET https://client.camb.ai/apis/list-voices` + `x-api-key` +(**200 = alive**, 401/403 = dead). It costs **zero credits** — do not use `tts-stream` for health. + +Credits cannot be read per API key: `GET /payments/credits/team/` answers `401 Unauthorized` +for an `x-api-key`/Bearer API key (it wants a user JWT). So the panel derives capacity as +`keys * 5000` and subtracts real TTS spends (`tts_credits` in the bank). + +Unit file used in production: + +```ini +[Unit] +Description=CAMB pool dashboard +After=network.target + +[Service] +Type=simple +ExecStart=/usr/bin/python3 /opt/camb-dash/dashboard.py --port 8823 \ + --bank /opt/camb-dash/camb_bank.jsonl --stats /opt/camb-dash/camb_stats.json \ + --shim http://127.0.0.1:8822 --refresh 900 +Restart=always +RestartSec=5 + +[Install] +WantedBy=multi-user.target +``` + +Caddy (behind an existing host, prefix mode — the page uses relative URLs on purpose): + +``` +redir /camb /camb/ 308 +handle_path /camb/* { + reverse_proxy 127.0.0.1:8823 +} +``` + +### Pitfalls + +* `--port` overrides env. In the Windows/MSYS shell `VAR=val cmd &` silently loses the + variable, so the panel kept binding its default port; argv is the only reliable path. +* Port 8899 is taken by the ZTE proxy on the workstation — two processes ended up + `LISTEN` on it (SO_REUSEADDR) and every request died as "remote end closed connection". + Pick a port that is really free (`ss -lnt`), not just "looks free". +* `team_id` in the bank can be an int — `str()` it before `.strip()` or the refresh thread dies. diff --git a/dashboard.py b/dashboard.py new file mode 100644 index 0000000..a670962 --- /dev/null +++ b/dashboard.py @@ -0,0 +1,311 @@ +#!/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() \ No newline at end of file