311 lines
12 KiB
Python
311 lines
12 KiB
Python
#!/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/<team_id> (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/<id>` 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 = """<!doctype html><html lang="ru"><head><meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||
<title>CAMB pool</title>
|
||
<style>
|
||
:root{--bg:#0d0f12;--card:#161a20;--line:#242b34;--fg:#e6e9ee;--dim:#8b95a3;--ok:#3ddc97;--bad:#ff5c7a;--acc:#6ea8ff}
|
||
*{box-sizing:border-box}
|
||
body{margin:0;background:var(--bg);color:var(--fg);font:14px/1.45 -apple-system,Segoe UI,Roboto,sans-serif}
|
||
header{padding:18px 22px;border-bottom:1px solid var(--line);display:flex;gap:14px;align-items:baseline;flex-wrap:wrap}
|
||
h1{font-size:18px;margin:0;font-weight:650}
|
||
.dim{color:var(--dim);font-size:12px}
|
||
main{padding:20px 22px;max-width:1180px;margin:0 auto}
|
||
.grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:12px;margin-bottom:22px}
|
||
.card{background:var(--card);border:1px solid var(--line);border-radius:10px;padding:14px}
|
||
.card .k{color:var(--dim);font-size:11px;text-transform:uppercase;letter-spacing:.06em}
|
||
.card .v{font-size:22px;font-weight:650;margin-top:6px}
|
||
table{width:100%;border-collapse:collapse;background:var(--card);border:1px solid var(--line);border-radius:10px;overflow:hidden}
|
||
th,td{padding:9px 12px;text-align:left;border-bottom:1px solid var(--line);font-size:13px}
|
||
th{color:var(--dim);font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.06em}
|
||
tr:last-child td{border-bottom:0}
|
||
.ok{color:var(--ok)}.bad{color:var(--bad)}
|
||
code{font-family:ui-monospace,Consolas,monospace;font-size:12px;color:var(--acc)}
|
||
button{background:#1e2630;color:var(--fg);border:1px solid var(--line);border-radius:8px;padding:7px 12px;cursor:pointer;font-size:13px}
|
||
button:hover{border-color:var(--acc)}
|
||
.bar{height:6px;background:#1e2630;border-radius:3px;overflow:hidden;margin-top:8px}
|
||
.bar>i{display:block;height:100%;background:linear-gradient(90deg,#3ddc97,#6ea8ff)}
|
||
</style></head><body>
|
||
<header><h1>CAMB.AI pool</h1><span class="dim" id="upd">loading…</span>
|
||
<button onclick="poke()">Обновить балансы</button></header>
|
||
<main>
|
||
<div class="grid" id="cards"></div>
|
||
<table><thead><tr><th>#</th><th>Аккаунт</th><th>team_id</th><th>Кредиты</th><th>Ключ</th><th>Статус</th></tr></thead>
|
||
<tbody id="rows"><tr><td colspan="6" class="dim">загрузка…</td></tr></tbody></table>
|
||
</main>
|
||
<script>
|
||
const fmt=n=>Number(n||0).toLocaleString('ru-RU');
|
||
async function load(){
|
||
const r=await fetch('api/stats',{cache:'no-store'}); const d=await r.json();
|
||
const t=d.totals||{};
|
||
document.getElementById('upd').textContent='обновлено '+new Date((t.updated||0)*1000).toLocaleTimeString('ru-RU')
|
||
+' · шим: '+(t.shim&&t.shim.status||'?')+' ('+(t.shim&&t.shim.live_keys||'?')+' ключей)';
|
||
const pct=t.credits_capacity?Math.min(100,100*(t.credits_left||0)/t.credits_capacity):0;
|
||
document.getElementById('cards').innerHTML=[
|
||
['Аккаунтов',fmt(t.accounts)],
|
||
['Ключей',fmt(t.keys)],
|
||
['Живых',fmt(t.alive)],
|
||
['Кредитов',fmt(t.credits_left)],
|
||
['Потрачено',fmt(t.spent)],
|
||
['Озвучек',fmt(t.tts_phrases)],
|
||
['Дубляжей',fmt(t.dubs)],
|
||
['В деньгах','$'+fmt(t.usd_value)]
|
||
].map(([k,v])=>`<div class="card"><div class="k">${k}</div><div class="v">${v}</div>${k==='Кредитов'?`<div class="bar"><i style="width:${pct}%"></i></div>`:''}</div>`).join('');
|
||
const rows=(d.accounts||[]).map((a,i)=>`<tr><td class="dim">${i+1}</td><td>${a.email||'—'}</td>
|
||
<td><code>${(a.team_id||'').slice(0,8)}</code></td>
|
||
<td class="${a.alive?'ok':'bad'}">${a.alive?fmt(a.credits_left):'—'}</td>
|
||
<td class="dim">${a.key_tail||'—'}</td>
|
||
<td class="${a.alive?'ok':'bad'}">${a.alive?'живой':'мёртвый'}</td></tr>`).join('');
|
||
document.getElementById('rows').innerHTML=rows||'<tr><td colspan="6" class="dim">пусто</td></tr>';
|
||
}
|
||
async function poke(){await fetch('api/refresh');setTimeout(load,3000);load();}
|
||
load();setInterval(load,30000);
|
||
</script></body></html>"""
|
||
|
||
|
||
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() |