import json import os import threading import time import urllib.error import urllib.request BASE = "https://api.kie.ai" POOL = os.environ.get("KIE_POOL", "/opt/grok-bot/kie_keys.jsonl") DEAD = os.environ.get("KIE_DEAD", "/opt/grok-bot/kie_keys_dead.jsonl") UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 " "(KHTML, like Gecko) Chrome/141.0.0.0 Safari/537.36") IMG_MODEL = os.environ.get("KIE_IMG_MODEL", "qwen2/text-to-image") # ~0.03 кредита IMG_MODEL_HI = os.environ.get("KIE_IMG_MODEL_HI", "z-image") # ~0.8 кредита VID_MODEL = os.environ.get("KIE_VID_MODEL", "hailuo/02-text-to-video-standard") _lock = threading.Lock() _keys = [] _rr = [0] def _load(): global _keys with _lock: if _keys: return _keys out, seen = [], set() try: with open(POOL, encoding="utf-8", errors="replace") as f: for line in f: line = line.strip() if not line: continue try: d = json.loads(line) k = (d.get("apiKey") or d.get("key") or d.get("api_key") or "").strip() except Exception: k = line if k and k not in seen: seen.add(k) out.append({"apiKey": k}) except FileNotFoundError: pass _keys = out return _keys def reload_pool(): global _keys with _lock: _keys = [] return len(_load()) def _kill(key): global _keys with _lock: try: with open(DEAD, "a", encoding="utf-8") as f: f.write(json.dumps({"apiKey": key, "ts": int(time.time())}) + "\n") except Exception: pass _keys = [x for x in _keys if x.get("apiKey") != key] def _next_key(): ks = _load() if not ks: raise RuntimeError("kie pool empty") with _lock: _rr[0] = (_rr[0] + 1) % len(ks) i = _rr[0] return ks[i]["apiKey"] def _req(key, path, body=None, timeout=45): h = {"User-Agent": UA, "Content-Type": "application/json", "Authorization": "Bearer " + key} data = json.dumps(body).encode() if body is not None else None req = urllib.request.Request(BASE + path, data=data, headers=h) try: return json.loads(urllib.request.urlopen(req, timeout=timeout).read().decode()) except urllib.error.HTTPError as e: try: return json.loads(e.read().decode()) except Exception: return {"code": e.code, "msg": "http"} except Exception as e: return {"code": -1, "msg": str(e)[:120]} def _create(model, inp): last = "" for _ in range(8): key = _next_key() r = _req(key, "/api/v1/jobs/createTask", {"model": model, "input": inp}) if r.get("code") == 200: d = r.get("data") or {} tid = d.get("taskId") or d.get("recordId") if tid: return tid, key msg = str(r.get("msg") or "") last = msg low = msg.lower() if r.get("code") == 402 or "credit" in low or "balance" in low or "квот" in low: _kill(key) continue time.sleep(2) raise RuntimeError("kie create: " + (last[:140] or "fail")) def _poll(tid, key, tmo=420): t0 = time.time() while time.time() - t0 < tmo: r = _req(key, "/api/v1/jobs/recordInfo?taskId=" + str(tid)) d = r.get("data") or {} st = d.get("state") if st == "success": rj = d.get("resultJson") or "{}" if isinstance(rj, str): try: rj = json.loads(rj) except Exception: rj = {} urls = rj.get("resultUrls") or rj.get("result_urls") or rj.get("urls") or [] return urls[0] if urls else None if st in ("fail", "failed"): raise RuntimeError("kie task fail: " + str(d.get("failMsg"))[:120]) time.sleep(6) raise RuntimeError("kie poll timeout") def _dl(url): req = urllib.request.Request(url, headers={"User-Agent": UA}) return urllib.request.urlopen(req, timeout=120).read() def kie_image_sync(prompt, aspect="1:1", hi=False): """-> bytes (jpeg/png/webp как отдал апстрим).""" model = IMG_MODEL_HI if hi else IMG_MODEL tid, key = _create(model, {"prompt": (prompt or "")[:900], "aspect_ratio": aspect}) url = _poll(tid, key, 300) if not url: raise RuntimeError("kie image: no url") return _dl(url) def kie_image_url(prompt, aspect="1:1", hi=False): model = IMG_MODEL_HI if hi else IMG_MODEL tid, key = _create(model, {"prompt": (prompt or "")[:900], "aspect_ratio": aspect}) return _poll(tid, key, 300) def kie_video_url(prompt, aspect="16:9", seconds=6): """hailuo/02 standard: ~5 кредитов/сек. Возвращает URL mp4.""" sec = max(6, min(int(seconds or 6), 10)) inp = {"prompt": (prompt or "")[:600], "duration": str(sec)} # часть моделей требует aspect_ratio/resolution — hailuo игнорирует лишнее, но не любит пустое inp["aspect_ratio"] = aspect tid, key = _create(VID_MODEL, inp) return _poll(tid, key, 600) def kie_video_sync(prompt, aspect="16:9", seconds=6, model=None): """Совместимость с патчем бота: -> (url, taskId-хвост).""" u = kie_video_url(prompt, aspect, seconds) return u, "" def status(): ks = _load() dead = 0 try: dead = sum(1 for _ in open(DEAD, encoding="utf-8", errors="replace")) except Exception: pass return {"keys": len(ks), "dead": dead, "img": IMG_MODEL, "vid": VID_MODEL}