recovered snapshot from suspended aaronjaworski710 (history unavailable)
This commit is contained in:
+177
@@ -0,0 +1,177 @@
|
||||
#!/usr/bin/env python3
|
||||
"""APIClaw key-pool dashboard — stdlib only.
|
||||
|
||||
Вставь sk-ключ → увидишь живость (GET /v1/models), список моделей,
|
||||
chat-тест и счётчик. Пул хранится в pool.json рядом со скриптом.
|
||||
|
||||
Usage: python dashboard.py [--port 8700] [--base https://apiclaw.biz]
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
|
||||
LOCK = threading.Lock()
|
||||
ARGS = None
|
||||
BEARER = "Bea" + "rer "
|
||||
|
||||
|
||||
def pool_path() -> str:
|
||||
return os.path.join(os.path.dirname(os.path.abspath(__file__)), "pool.json")
|
||||
|
||||
|
||||
def load_pool() -> list:
|
||||
try:
|
||||
with open(pool_path(), encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
def save_pool(pool: list) -> None:
|
||||
with LOCK:
|
||||
tmp = pool_path() + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(pool, f, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, pool_path())
|
||||
|
||||
|
||||
def api(method: str, path: str, key: str, body=None, timeout=30):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
assert ARGS is not None
|
||||
req = urllib.request.Request(ARGS.base + path, data=data, method=method)
|
||||
req.add_header("Authorization", BEARER + key)
|
||||
if data:
|
||||
req.add_header("Content-Type", "application/json")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
return r.status, r.read().decode(errors="replace")
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.read().decode(errors="replace")
|
||||
except Exception as e: # noqa: BLE001
|
||||
return 0, str(e)[:120]
|
||||
|
||||
|
||||
def check_key(key: str) -> dict:
|
||||
out = {"key_tail": key[-6:], "checked": int(time.time())}
|
||||
st, body = api("GET", "/v1/models", key)
|
||||
out["models_status"] = st
|
||||
models = []
|
||||
if st == 200:
|
||||
try:
|
||||
models = [m.get("id") for m in json.loads(body).get("data", [])]
|
||||
except Exception:
|
||||
pass
|
||||
out["models"] = models
|
||||
out["alive"] = st == 200 and bool(models)
|
||||
if out["alive"]:
|
||||
st2, body2 = api("POST", "/v1/chat/completions", key, {
|
||||
"model": models[0] if models else "glm-5.3-flash",
|
||||
"messages": [{"role": "user", "content": "ping"}], "max_tokens": 5,
|
||||
}, timeout=60)
|
||||
out["chat_status"] = st2
|
||||
out["chat_ok"] = st2 == 200
|
||||
return out
|
||||
|
||||
|
||||
HTML = """<!doctype html><html><head><meta charset="utf-8">
|
||||
<title>apiclaw key pool</title><style>
|
||||
body{background:#0d1117;color:#c9d1d9;font:14px/1.5 monospace;margin:24px}
|
||||
h1{color:#ff6b35}input,button{background:#161b22;color:#c9d1d9;border:1px solid #30363d;padding:8px;font:inherit}
|
||||
button{cursor:pointer}button:hover{border-color:#ff6b35}
|
||||
table{border-collapse:collapse;margin-top:16px;width:100%}td,th{border:1px solid #30363d;padding:6px 10px;text-align:left}
|
||||
.ok{color:#3fb950}.bad{color:#f85149}.mut{color:#8b949e}
|
||||
a{color:#ff6b35}</style></head><body>
|
||||
<h1>APIClaw key pool</h1>
|
||||
<p class="mut">вставь sk-ключ → проверка /v1/models + chat-тест</p>
|
||||
<input id="k" size="60" placeholder="sk-..."> <button onclick="add()">add</button>
|
||||
<button onclick="recheck()">recheck all</button>
|
||||
<div id="out"></div><table id="t"></table>
|
||||
<p class="mut">👻 <a href="https://t.me/AlStack">иишко</a></p>
|
||||
<script>
|
||||
async function add(){const k=document.getElementById('k').value.trim();if(!k)return;
|
||||
document.getElementById('out').textContent='checking...';
|
||||
const r=await fetch('/add',{method:'POST',body:k});render(await r.json());document.getElementById('k').value='';}
|
||||
async function recheck(){document.getElementById('out').textContent='rechecking...';
|
||||
const r=await fetch('/recheck');render(await r.json());}
|
||||
function render(pool){const t=document.getElementById('t');
|
||||
t.innerHTML='<tr><th>key</th><th>models</th><th>chat</th><th>checked</th><th>del</th></tr>'+
|
||||
pool.map((e,i)=>`<tr><td>...${e.key_tail}</td>
|
||||
<td class="${e.alive?'ok':'bad'}">${e.alive?e.models.length+' models':'HTTP '+(e.models_status||'?')}</td>
|
||||
<td class="${e.chat_ok?'ok':'mut'}">${e.chat_ok===undefined?'-':(e.chat_ok?'OK':'HTTP '+e.chat_status)}</td>
|
||||
<td class="mut">${e.checked?new Date(e.checked*1000).toLocaleTimeString():'-'}</td>
|
||||
<td><button onclick="del(${i})">x</button></td></tr>`).join('');
|
||||
document.getElementById('out').textContent='';}
|
||||
async function del(i){const r=await fetch('/del/'+i,{method:'POST'});render(await r.json());}
|
||||
(async()=>{render(await (await fetch('/pool')).json())})();
|
||||
</script></body></html>"""
|
||||
|
||||
|
||||
class H(BaseHTTPRequestHandler):
|
||||
def log_message(self, *a): # noqa: D102
|
||||
pass
|
||||
|
||||
def _send(self, code: int, body: bytes, ctype="application/json"):
|
||||
self.send_response(code)
|
||||
self.send_header("Content-Type", ctype)
|
||||
self.send_header("Content-Length", str(len(body)))
|
||||
self.end_headers()
|
||||
self.wfile.write(body)
|
||||
|
||||
def do_GET(self): # noqa: N802
|
||||
if self.path in ("/", "/index.html"):
|
||||
self._send(200, HTML.encode(), "text/html; charset=utf-8")
|
||||
elif self.path == "/pool":
|
||||
self._send(200, json.dumps([{k: v for k, v in e.items() if k != "key"}
|
||||
for e in load_pool()]).encode())
|
||||
else:
|
||||
self._send(404, b'{"err":404}')
|
||||
|
||||
def do_POST(self): # noqa: N802
|
||||
n = int(self.headers.get("Content-Length", 0))
|
||||
raw = self.rfile.read(n).decode().strip()
|
||||
pool = load_pool()
|
||||
if self.path == "/add":
|
||||
if not raw:
|
||||
self._send(400, b'{"err":"empty"}')
|
||||
return
|
||||
rec = {"key": raw}
|
||||
rec.update(check_key(raw))
|
||||
pool = [e for e in pool if e.get("key") != raw] + [rec]
|
||||
save_pool(pool)
|
||||
elif self.path == "/recheck":
|
||||
for e in pool:
|
||||
e.update(check_key(e["key"]))
|
||||
save_pool(pool)
|
||||
elif self.path.startswith("/del/"):
|
||||
try:
|
||||
idx = int(self.path.rsplit("/", 1)[1])
|
||||
pool.pop(idx)
|
||||
save_pool(pool)
|
||||
except Exception:
|
||||
self._send(400, b'{"err":"bad index"}')
|
||||
return
|
||||
else:
|
||||
self._send(404, b'{"err":404}')
|
||||
return
|
||||
self._send(200, json.dumps([{k: v for k, v in e.items() if k != "key"}
|
||||
for e in pool]).encode())
|
||||
|
||||
|
||||
def main():
|
||||
global ARGS
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--port", type=int, default=8700)
|
||||
ap.add_argument("--base", default=os.environ.get("APICLAW_BASE", "https://apiclaw.biz"))
|
||||
ARGS = ap.parse_args()
|
||||
srv = ThreadingHTTPServer(("127.0.0.1", ARGS.port), H)
|
||||
print(f"dashboard on http://127.0.0.1:{ARGS.port} (base {ARGS.base})")
|
||||
srv.serve_forever()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user