Initial public release. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
115 lines
4.0 KiB
Python
115 lines
4.0 KiB
Python
#!/usr/bin/env python3
|
|
import os
|
|
import re
|
|
import sqlite3
|
|
import sys
|
|
import time
|
|
|
|
GW_DB = os.environ.get("IISHKO_GW_DB", "/opt/grok-gateway/new-api/one-api.db")
|
|
BOT_SRC = "/opt/grok-bot/iishko_bot.py" # [BOTFIX 2310] живой активный сервис
|
|
BOT_SRC_FALLBACK = "/opt/grok-bot/grok_bot.py" # старое имя (legacy)
|
|
TIER_GROUPS = ("t1", "t2", "t3", "t4")
|
|
|
|
LIVE_SQL = ("SELECT COUNT(*) FROM abilities a JOIN channels c ON c.id=a.channel_id "
|
|
"WHERE a.model=? AND a.enabled=1 AND c.status=1 "
|
|
"AND instr(',' || replace(c.models,' ','') || ',', ',' || a.model || ',')>0") # [FIX-2410] containment как в repair
|
|
|
|
|
|
def _read_src(path):
|
|
try:
|
|
with open(path, encoding="utf-8") as f:
|
|
return f.read()
|
|
except OSError as e:
|
|
print(time.strftime("%F %T"), "cannot read", path, str(e)[:120], flush=True)
|
|
return ""
|
|
|
|
|
|
def _parse_tiers(src):
|
|
m = re.search(r"^TIER_MODELS\s*=\s*\{(.*?)^\s*\}", src, re.S | re.M)
|
|
if not m:
|
|
return {}
|
|
body = re.sub(r"#[^\n]*", "", m.group(1))
|
|
tiers = {}
|
|
for tm in re.finditer(r"(\d+)\s*:\s*\[(.*?)\]", body, re.S):
|
|
names = re.findall(r"""["']([A-Za-z0-9._/\-]+)["']""", tm.group(2))
|
|
if names:
|
|
tiers[int(tm.group(1))] = sorted(set(names))
|
|
return tiers
|
|
|
|
|
|
def catalog_tiers(path=None):
|
|
"""Список тиров из исходника бота (без импорта бота).
|
|
path=None: сначала живой iishko_bot.py (BOT_SRC), затем legacy grok_bot.py."""
|
|
paths = (path,) if path else (BOT_SRC, BOT_SRC_FALLBACK)
|
|
for p in paths:
|
|
tiers = _parse_tiers(_read_src(p))
|
|
if tiers:
|
|
return tiers
|
|
return {}
|
|
|
|
|
|
def catalog_models(tiers):
|
|
"""Union моделей каталога (для отчёта dark)."""
|
|
return sorted({m for ms in tiers.values() for m in ms})
|
|
|
|
|
|
def repair_abilities(con, tiers):
|
|
if not tiers:
|
|
return 0
|
|
models = catalog_models(tiers)
|
|
order = [n for n in sorted(tiers) if 1 <= n <= 4]
|
|
if not models or not order:
|
|
return 0
|
|
|
|
def ph(n):
|
|
return ",".join(["?"] * n)
|
|
|
|
params = list(models) + list(TIER_GROUPS)
|
|
gate_parts = ['abilities."group" NOT IN (' + ph(len(TIER_GROUPS)) + ')']
|
|
for n in order:
|
|
cum = [m for i in order if i <= n for m in tiers[i]]
|
|
if not cum:
|
|
continue
|
|
gate_parts.append('(abilities."group"=? AND abilities.model IN ('
|
|
+ ph(len(cum)) + '))')
|
|
params.append("t" + str(n))
|
|
params.extend(cum)
|
|
# [FIX-2410] Нормализация containment: c.models может быть «m1, m2» с пробелами —
|
|
sql = ("UPDATE abilities SET enabled=1 WHERE enabled=0 AND model IN ("
|
|
+ ph(len(models)) + ") "
|
|
+ "AND EXISTS (SELECT 1 FROM channels c WHERE c.id=abilities.channel_id "
|
|
"AND c.status=1 AND instr(',' || replace(c.models,' ','') || ',', "
|
|
"',' || abilities.model || ',')>0) "
|
|
+ "AND (" + " OR ".join(gate_parts) + ")")
|
|
return con.execute(sql, params).rowcount
|
|
|
|
|
|
def main():
|
|
tiers = catalog_tiers()
|
|
if not tiers:
|
|
print(time.strftime("%F %T"), "no catalog tiers parsed - refusing to touch abilities",
|
|
flush=True)
|
|
return 1
|
|
models = catalog_models(tiers)
|
|
con = sqlite3.connect(GW_DB, timeout=60)
|
|
try:
|
|
con.execute("PRAGMA busy_timeout=60000")
|
|
fixed = repair_abilities(con, tiers)
|
|
con.commit()
|
|
dark = [m for m in models if not con.execute(LIVE_SQL, (m,)).fetchone()[0]]
|
|
con.close()
|
|
except Exception as e:
|
|
print(time.strftime("%F %T"), "ERROR", str(e)[:200], flush=True)
|
|
try:
|
|
con.rollback()
|
|
except Exception:
|
|
pass
|
|
return 2
|
|
print(time.strftime("%F %T"), "catalog=%d re-enabled=%d dark=%s"
|
|
% (len(models), fixed, ",".join(dark) if dark else "none"), flush=True)
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(main())
|