Files
acemusic-autoreg/ace_shim.py
T

389 lines
15 KiB
Python

#!/usr/bin/env python3
# ace-shim: пул аккаунтов acemusic.ai -> POST /v1/music/generations (stdlib, без зависимостей)
# банк: /opt/ace-shim/bank.jsonl строки {email,password,uid,credits,cookies:{ace_at,ace_rt,ace_flow}}
import json, os, sys, time, threading, uuid, urllib.request, urllib.error, urllib.parse, traceback
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
BASE = "https://acemusic.ai"
BANK = os.environ.get("ACE_BANK", "/opt/ace-shim/bank.jsonl")
STATE = os.environ.get("ACE_STATE", "/opt/ace-shim/state.json")
PORT = int(os.environ.get("ACE_PORT", "48960"))
UA = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/145.0.0.0 Safari/537.36"
SONG_COST = 4
LOCK = threading.RLock()
BUSY = set()
STATE_LOCK = threading.Lock()
STATS = {"gen_ok": 0, "gen_fail": 0}
def load_state():
try:
with open(STATE) as f:
return json.load(f)
except Exception:
return {}
STATE_D = load_state()
def save_state():
with STATE_LOCK:
tmp = STATE + ".tmp"
with open(tmp, "w") as f:
json.dump(STATE_D, f)
os.replace(tmp, STATE)
def st(uid):
return STATE_D.setdefault(str(uid), {"credits": None, "ts": 0, "dead": False, "name": ""})
def load_bank():
accs = []
try:
with open(BANK) as f:
for line in f:
line = line.strip()
if not line:
continue
try:
r = json.loads(line)
except Exception:
continue
if r.get("email") and r.get("password"):
accs.append(r)
except Exception:
pass
return accs
def save_bank(accs):
tmp = BANK + ".tmp"
with open(tmp, "w") as f:
for r in accs:
f.write(json.dumps(r) + "\n")
os.replace(tmp, BANK)
class Acc:
def __init__(self, rec):
self.rec = rec
self.uid = str(rec.get("uid") or "")
self.email = rec.get("email")
self.pw = rec.get("password")
ck = rec.get("cookies") or {}
self.cookies = {k: v for k, v in ck.items() if v}
def _headers(self, extra=None):
h = {
"User-Agent": UA,
"Origin": BASE,
"Referer": BASE + "/create/",
"Accept": "application/json, text/plain, */*",
"Cookie": "; ".join("%s=%s" % (k, v) for k, v in self.cookies.items()),
}
if extra:
h.update(extra)
return h
def _raw(self, path, data=None, method=None, timeout=45):
body = None
h = self._headers()
if data is not None:
body = json.dumps(data).encode()
h["Content-Type"] = "application/json"
req = urllib.request.Request(BASE + path, data=body, headers=h, method=method or ("POST" if body else "GET"))
try:
with urllib.request.urlopen(req, timeout=timeout) as r:
return r.status, r.read().decode("utf-8", "replace"), r.headers
except urllib.error.HTTPError as e:
return e.code, e.read().decode("utf-8", "replace"), e.headers
except Exception as e:
return 0, "ERR %s" % e, {}
def login(self):
"""перелогин по email/паролю -> свежие cookies"""
body = {"email": self.email, "password": self.pw, "next": "/create/", "plan": None, "cycle": None}
req = urllib.request.Request(BASE + "/auth/login", data=json.dumps(body).encode(),
headers={"User-Agent": UA, "Content-Type": "application/json",
"Origin": BASE, "Referer": BASE + "/login/"}, method="POST")
try:
with urllib.request.urlopen(req, timeout=45) as r:
raw = r.read().decode("utf-8", "replace")
hdrs = r.headers.get_all("Set-Cookie") or []
except urllib.error.HTTPError as e:
return False, "%s %s" % (e.code, e.read().decode("utf-8", "replace")[:120])
except Exception as e:
return False, "login err %s" % e
got = {}
for h in hdrs:
m = h.split(";")[0]
if "=" in m:
k, v = m.split("=", 1)
if k in ("ace_at", "ace_rt", "ace_flow"):
got[k] = v
if not got.get("ace_at"):
return False, "no ace_at in login %s" % raw[:120]
self.cookies.update(got)
self.rec["cookies"] = {k: self.cookies.get(k) for k in ("ace_at", "ace_rt", "ace_flow")}
s = st(self.uid)
s["dead"] = False
save_state()
return True, "login ok"
def status(self, timeout=30):
code, txt, _ = self._raw("/api/status", timeout=timeout)
if code == 200:
try:
return json.loads(txt)
except Exception:
return None
return None
def idea(self, prompt, instrumental=False):
body = {
"prompt": prompt[:2000],
"created_at": int(time.time() * 1000),
"references": [],
"model": "acemusic-v1",
"analytics": {"attempt_id": str(uuid.uuid4()), "requested_model": "acemusic-v1"},
"media": [],
}
if instrumental:
body["instrumental"] = True
return self._raw("/api/idea", data=body, timeout=60)
def songs(self):
code, txt, _ = self._raw("/api/songs", timeout=45)
if code != 200:
return None
try:
return json.loads(txt).get("items", [])
except Exception:
return None
def pick_acc(need=SONG_COST):
"""выбирает аккаунт с запасом кредитов; под локом помечает busy"""
with LOCK:
accs = load_bank()
if not accs:
return None
# сначала те, у кого известны кредиты
cands = []
for rec in accs:
uid = str(rec.get("uid"))
s = st(uid)
if s.get("dead") or uid in BUSY:
continue
cr = s.get("credits")
if cr is None:
cr = rec.get("credits")
if cr is not None and cr < need:
continue
cands.append((0 if cr is None else 1, -(cr or 0), rec))
cands.sort(key=lambda x: (x[0], x[1]))
for _, _, rec in cands[:6]:
a = Acc(rec)
uid = a.uid
s = st(uid)
if s.get("credits") is None or time.time() - (s.get("ts") or 0) > 900:
snap = a.status()
if snap:
s["credits"] = snap["user"]["credits"]
s["ts"] = time.time()
s["name"] = snap["user"].get("name") or ""
save_state()
if (s.get("credits") or 0) < need:
continue
BUSY.add(uid)
return a
return None
def release(a):
with LOCK:
BUSY.discard(a.uid)
def generate(prompt, instrumental=False, timeout=420):
a = pick_acc()
if not a:
return {"ok": False, "error": "pool_empty", "detail": "нет аккаунтов с кредитами"}
try:
code, txt, _ = a.idea(prompt, instrumental)
if code == 401:
ok, det = a.login()
if not ok:
s = st(a.uid); s["dead"] = True; save_state()
return {"ok": False, "error": "auth", "detail": det}
code, txt, _ = a.idea(prompt, instrumental)
if code != 202:
if code in (401, 403):
s = st(a.uid); s["dead"] = True; save_state()
return {"ok": False, "error": "submit_%s" % code, "detail": txt[:200]}
try:
task_id = json.loads(txt)["song"]["task_id"]
except Exception:
return {"ok": False, "error": "parse", "detail": txt[:200]}
# списываем локально сразу
s = st(a.uid)
if s.get("credits") is not None:
s["credits"] = max(0, s["credits"] - SONG_COST)
s["ts"] = time.time()
save_state()
t0 = time.time()
while time.time() - t0 < timeout:
time.sleep(7)
items = a.songs()
if items is None:
continue
hit = [x for x in items if x.get("task_id") == task_id]
if not hit:
continue
it = hit[0]
status = it.get("status")
if status in ("succeeded", "done", "ready", "completed"):
rel = it.get("local_audio")
if not rel:
return {"ok": False, "error": "no_audio", "detail": json.dumps(it)[:300]}
dur = (it.get("result") or {}).get("duration_sec")
title = (it.get("meta") or {}).get("title") or prompt[:60]
STATS["gen_ok"] += 1
out = {
"ok": True,
"model": "ace-music",
"tracks": [{"audioUrl": BASE + rel, "title": title, "duration": dur,
"coverUrl": (BASE + it["local_cover"]) if it.get("local_cover") else None}],
"task_id": task_id,
"duration": dur,
"credits_left": s.get("credits"),
"account": a.email,
}
try:
# освежаем реальный остаток
snap = a.status()
if snap:
s["credits"] = snap["user"]["credits"]
save_state()
out["credits_left"] = s["credits"]
except Exception:
pass
return out
if status in ("failed", "error", "canceled"):
STATS["gen_fail"] += 1
return {"ok": False, "error": "gen_failed", "detail": json.dumps(it)[:300]}
return {"ok": False, "error": "timeout", "detail": "task %s > %ss" % (task_id, timeout)}
finally:
release(a)
def reviver_loop():
"""раз в час: перелогин исчерпанных/помеченных dead аккаунтов (месячный сброс кредитов, протухшие cookies)"""
while True:
time.sleep(3600)
try:
accs = load_bank()
n = 0
changed = False
for rec in accs:
uid = str(rec.get("uid"))
s = st(uid)
low = (s.get("credits") is None) or (s.get("credits") or 0) < SONG_COST
if not (s.get("dead") or low):
continue
if time.time() - (s.get("ts") or 0) < 3 * 3600:
continue
a = Acc(rec)
ok, det = a.login()
if not ok:
continue
snap = a.status()
if snap:
s["credits"] = snap["user"]["credits"]
s["ts"] = time.time()
s["dead"] = False
s["name"] = snap["user"].get("name") or ""
changed = True
n += 1
if n % 20 == 0:
save_state()
save_state()
if changed:
save_bank(accs)
print("reviver: refreshed %d" % n, flush=True)
except Exception:
traceback.print_exc()
def pool_status():
accs = load_bank()
alive = 0
total_cr = 0
rows = []
for rec in accs:
uid = str(rec.get("uid"))
s = st(uid)
cr = s.get("credits")
if cr is None:
cr = rec.get("credits")
if s.get("dead"):
rows.append({"uid": uid, "email": rec.get("email"), "credits": cr, "dead": True})
continue
alive += 1
total_cr += (cr or 0)
rows.append({"uid": uid, "email": rec.get("email"), "credits": cr, "dead": False})
return {"ok": True, "accounts": len(accs), "alive": alive, "credits_total": total_cr,
"songs_capacity": total_cr // SONG_COST, "busy": len(BUSY), "stats": STATS,
"items": rows[:400]}
class H(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"
def _send(self, code, payload, ctype="application/json"):
data = payload if isinstance(payload, bytes) else json.dumps(payload, ensure_ascii=False).encode()
self.send_response(code)
self.send_header("Content-Type", ctype)
self.send_header("Content-Length", str(len(data)))
self.send_header("Access-Control-Allow-Origin", "*")
self.end_headers()
try:
self.wfile.write(data)
except Exception:
pass
def do_GET(self):
p = urllib.parse.urlparse(self.path).path
if p in ("/healthz", "/v1/music/health", "/"):
return self._send(200, pool_status())
if p.startswith("/v1/music/files/"):
return self._proxy_file(p[len("/v1/music/files/"):])
return self._send(404, {"error": "not_found"})
def _proxy_file(self, name):
name = urllib.parse.unquote(name)
if not name.endswith(".mp3") or "/" in name or ".." in name:
return self._send(400, {"error": "bad_name"})
url = BASE + "/data/" + name
try:
req = urllib.request.Request(url, headers={"User-Agent": UA, "Referer": BASE + "/create/"})
with urllib.request.urlopen(req, timeout=120) as r:
data = r.read()
return self._send(200, data, "audio/mpeg")
except Exception as e:
return self._send(502, {"error": "upstream", "detail": str(e)[:200]})
def do_POST(self):
p = urllib.parse.urlparse(self.path).path
n = int(self.headers.get("Content-Length") or 0)
raw = self.rfile.read(n) if n else b"{}"
try:
body = json.loads(raw.decode("utf-8", "replace") or "{}")
except Exception:
return self._send(400, {"error": "bad_json"})
if p in ("/v1/music/generations", "/v1/audio/generations", "/generate"):
prompt = (body.get("prompt") or body.get("input") or "").strip()
if not prompt:
return self._send(400, {"ok": False, "error": "empty_prompt"})
tmo = int(body.get("timeout") or 420)
tmo = max(60, min(tmo, 900))
res = generate(prompt, bool(body.get("instrumental")), timeout=tmo)
return self._send(200 if res.get("ok") else 502, res)
return self._send(404, {"error": "not_found"})
def log_message(self, *a):
pass
if __name__ == "__main__":
print("ace-shim on :%d bank=%s accounts=%d" % (PORT, BANK, len(load_bank())), flush=True)
threading.Thread(target=reviver_loop, daemon=True).start()
ThreadingHTTPServer(("0.0.0.0", PORT), H).serve_forever()