Files
reformandClaude Opus 5.5 0ee6fb843b
checks / pytest (push) Has been cancelled
checks / moderation (push) Has been cancelled
checks / node (push) Has been cancelled
IISHKO: Telegram bot, Mini App and gateway
Initial public release.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 21:51:30 +03:00

125 lines
5.3 KiB
Python

import asyncio, json, os, time
import aiohttp
KEYS_FILE = os.environ.get("PIKEYS", "/opt/grok-bot/piapi_keys.jsonl")
API = "https://api.piapi.ai"
_sem = asyncio.Semaphore(2)
_dead = {}
def _load_keys():
keys = []
try:
with open(KEYS_FILE, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line:
continue
try:
rec = json.loads(line)
except Exception:
continue
k = rec.get("key")
if k and k not in keys:
keys.append(k)
except FileNotFoundError:
pass
return keys
def _alive_keys():
now = time.time()
return [k for k in _load_keys() if now - _dead.get(k, 0) > 3600]
def _headers(key):
return {"x-api-key": key, "Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/131.0.0.0 Safari/537.36"}
async def pool_status():
keys = _load_keys()
alive = _alive_keys()
return {"backend": "piapi-udio", "total": len(keys), "alive": len(alive), "dead": len(keys) - len(alive)}
async def generate_music(prompt, title=None, style=None, instrumental=False,
model_version=None, timeout=480):
keys = _alive_keys()
if not keys:
return {"ok": False, "error": "POOL_EMPTY", "tracks": [], "key_tail": ""}
desc = prompt
if style:
desc = "%s, %s" % (style, prompt) if prompt != style else style
if title:
desc = "%s (%s)" % (desc, title)
inp = {"gpt_description_prompt": desc[:1000], "negative_tags": "",
"lyrics_type": "instrumental" if instrumental else "generate", "seed": -1}
body = {"model": "music-u", "task_type": "generate_music", "input": inp,
"config": {"service_mode": "public", "webhook_config": {"endpoint": "", "secret": ""}}}
async with _sem:
last_err = None
for key in keys:
try:
async with aiohttp.ClientSession() as s:
async with s.post(API + "/api/v1/task", headers=_headers(key), json=body,
timeout=aiohttp.ClientTimeout(total=40)) as r:
txt = await r.text()
if r.status in (401, 403):
_dead[key] = time.time()
last_err = "KEY_DEAD_%d" % r.status
continue
try:
d = json.loads(txt)
except Exception:
last_err = "BAD_JSON"
continue
if r.status != 200:
msg = str(d.get("message") or d.get("error") or txt)[:150].lower()
if "balance" in msg or "credit" in msg or "insufficient" in msg or "point" in msg:
_dead[key] = time.time()
last_err = "NO_CREDITS"
else:
last_err = "HTTP_%d:%s" % (r.status, txt[:120])
continue
tid = (d.get("data") or {}).get("task_id")
if not tid:
last_err = "NO_TASKID:%s" % txt[:120]
continue
t0 = time.time()
while time.time() - t0 < timeout:
await asyncio.sleep(10)
try:
async with aiohttp.ClientSession() as s2:
async with s2.get(API + "/api/v1/task/" + str(tid),
headers=_headers(key),
timeout=aiohttp.ClientTimeout(total=25)) as gr:
gd = await gr.json()
except Exception:
continue
dd = gd.get("data") or {}
st = str(dd.get("status", "")).lower()
if st == "completed":
songs = ((dd.get("output") or {}).get("songs")) or []
out = [{"audioUrl": s.get("song_path") or s.get("hosted_audio_url"),
"title": s.get("title") or title or "track",
"imageUrl": s.get("image_path")}
for s in songs if (s.get("song_path") or s.get("hosted_audio_url"))]
return {"ok": bool(out), "tracks": out, "job": tid,
"key_tail": key[-6:], "error": None if out else "NO_TRACKS"}
if st in ("failed", "failure", "error", "cancelled"):
err = (dd.get("error") or {}).get("message") if isinstance(dd.get("error"), dict) else str(dd.get("error"))
err = (err or "")[:150].lower()
if "balance" in err or "credit" in err or "insufficient" in err:
_dead[key] = time.time()
last_err = "NO_CREDITS"
else:
last_err = "TASK_FAILED:%s" % (err or st)
break
else:
last_err = "TIMEOUT"
except Exception as e:
last_err = "EXC:%s" % str(e)[:100]
return {"ok": False, "error": last_err or "UNKNOWN", "tracks": [], "key_tail": keys[-1][-6:] if keys else ""}