Spaces:
Running
Running
Download vb_aa.py from jay0826/discord-bot: direct link, hf CLI and curl.
- Browser
- Download file 12.5 kB
-
https://huggingface.co/spaces/jay0826/discord-bot/resolve/main/vb_aa.py
- Command line
-
hf download hf://spaces/jay0826/discord-bot/vb_aa.py
-
curl -L -o vb_aa.py https://huggingface.co/spaces/jay0826/discord-bot/resolve/main/vb_aa.py
12.5 kB
| # -*- coding: utf-8 -*- | |
| """Artificial Analysis Intelligence Index(AA 綜合智力指數)。 | |
| ★2026-11-24 主人:「/model 改成由 AA score 評分;各家路由不能代表模型能力」。 | |
| /model 清單照這個分數排;/admin swap、compare、週報有分數時也改看它(LMArena 中文榜留著當第二個數字)。 | |
| ★來源:免費 Data API GET https://artificialanalysis.ai/api/v2/language/models/free | |
| · 標頭 x-api-key(HF Secret AA_API_KEY;主人自己申請,這裡不經手、不印) | |
| · 分頁(page=1,2…,每頁 200 支,看 pagination.has_more) | |
| · 分數在 data[].evaluations.artificial_analysis_intelligence_index(可能是 null=沒測,不是 0) | |
| · 免費每 24 小時 100 次:一天抓一次(約 2 頁);失敗 RETRY_S 後再試 | |
| · 規定要標示來源 → ATTRIB(顯示分數的地方附上) | |
| ★對名字:跟中文榜同一套規則(vb_arena._norm/_loose),另外把「.」當「-」(AA 的 slug 是 glm-5-3,我們是 glm-5.3)。 | |
| 一模一樣才算「準」;只差版本尾巴(日期、-instruct、量化…)算「≈」;括號註記(Max、Reasoning…)正規化後撞名取分數高的。 | |
| ★更新:開機先讀回上次存的(Supabase user_notes 的 __aa_index__),FIRST_DELAY 秒後抓新的,之後每天一次。 | |
| ★純邏輯+可注入 HTTP(get),可以直接測。 | |
| """ | |
| import json | |
| import re | |
| import threading | |
| import time | |
| from typing import Any, Callable, Dict, List, Optional | |
| import vb_arena as _A | |
| URL = "https://artificialanalysis.ai/api/v2/language/models/free" | |
| STORE_USER = "__aa_index__" | |
| TIMEOUT_S = 30 | |
| MAX_PAGES = 10 | |
| PAGE_GAP_S = 1.5 | |
| FIRST_DELAY = 90.0 | |
| REFRESH_S = 86400.0 | |
| RETRY_S = 3 * 3600.0 # 免費 100 次/24 小時:失敗也別一直打 | |
| TIE = 2.0 # 差這麼多分以內=差不多 | |
| BETTER_BY = 3.0 # 週報「可以考慮換」的門檻(AA 分數) | |
| FLAGSHIP_PCT = 0.6 # 內部分級(不顯示):分數在全部模型的前 40% 算「旗艦」那組 | |
| ATTRIB = "分數:Artificial Analysis(https://artificialanalysis.ai/)" | |
| UA = "VanillaBot/1.0 (Discord bot; https://jay0826-discord-bot.hf.space)" | |
| _LOCK = threading.Lock() | |
| _S: Dict[str, Any] = {"exact": {}, "loose": {}, "ver": None, "n": 0, "at": None, "n_ok": 0, "n_fail": 0, | |
| "err": "", "thread": False, "from_store": False, "cut": None} | |
| _CFG: Dict[str, Any] = {"load": None, "save": None, "key": None} | |
| def _norm(name: str) -> str: | |
| return re.sub(r"-{2,}", "-", _A._norm(name).replace(".", "-")).strip("-") | |
| def _loose(name: str) -> str: | |
| parts = _norm(name).split("-") | |
| while len(parts) > 1 and (parts[-1] in _A._SUFFIX or _A._DATE.match(parts[-1])): | |
| parts.pop() | |
| return "-".join(parts) | |
| _SIZE_TOK = re.compile(r"^a?\d+(?:-\d+)?[bm]$") # 120b、a12b、1-5b(「.」已經變成「-」) | |
| def _strip_size(n: str) -> str: | |
| """★2026-11-26 我們的 nemotron-3.5-super-vl-120b-a12b,AA 上叫 nemotron-3-5-super-vl(不寫參數量)。 | |
| 去掉結尾的參數量標記;只拿來對 AA 上**本來就不寫參數量**的名字(exact),qwen3.8-235b 不會被對到 qwen3.8-27b。""" | |
| parts = n.split("-") | |
| while len(parts) > 1 and _SIZE_TOK.match(parts[-1]): | |
| parts.pop() | |
| return "-".join(parts) | |
| def _get_json(url: str, params: Dict[str, Any], key: str) -> Dict[str, Any]: | |
| import requests | |
| r = requests.get(url, params=params, headers={"x-api-key": key, "User-Agent": UA}, timeout=TIMEOUT_S) | |
| r.raise_for_status() | |
| return r.json() | |
| def configure(load: Optional[Callable[[], Optional[str]]] = None, save: Optional[Callable[[str], None]] = None, | |
| key: Optional[Callable[[], str]] = None) -> None: | |
| _CFG.update(load=load, save=save, key=key) | |
| def _api_key() -> str: | |
| fn = _CFG.get("key") | |
| try: | |
| return str(fn() or "") if fn else "" | |
| except Exception: | |
| return "" | |
| def fetch(get: Optional[Callable[[str, Dict[str, Any], str], Dict[str, Any]]] = None, | |
| sleep: Callable[[float], None] = time.sleep, now: Optional[float] = None) -> bool: | |
| """抓整份(分頁),成功才換掉舊的(並存檔)。回有沒有成功。""" | |
| key = _api_key() | |
| if not key: | |
| _S["err"] = "沒設 AA_API_KEY" | |
| return False | |
| g = get or _get_json | |
| t = time.time() if now is None else now | |
| rows: List[Dict[str, Any]] = [] | |
| ver = None | |
| try: | |
| for page in range(1, MAX_PAGES + 1): | |
| d = g(URL, {"page": page}, key) | |
| ver = d.get("intelligence_index_version", ver) | |
| rows += list(d.get("data") or []) | |
| if not (d.get("pagination") or {}).get("has_more"): | |
| break | |
| sleep(PAGE_GAP_S) | |
| except Exception as e: | |
| code = getattr(getattr(e, "response", None), "status_code", None) | |
| _S.update(err="%s%s" % (type(e).__name__, (" HTTP %s" % code) if code else ""), n_fail=_S["n_fail"] + 1) | |
| return False | |
| recs = [{"name": str(r.get("name") or ""), "slug": str(r.get("slug") or ""), | |
| "score": (r.get("evaluations") or {}).get("artificial_analysis_intelligence_index")} for r in rows] | |
| if not _install(recs, t, ver): | |
| _S.update(err="回應裡沒有分數(格式變了?)", n_fail=_S["n_fail"] + 1) | |
| return False | |
| _S["n_ok"] += 1 | |
| save = _CFG.get("save") | |
| if save is not None: | |
| try: | |
| save(dumps()) | |
| except Exception as e: | |
| _S["err"] = "存檔 %s" % type(e).__name__ | |
| return True | |
| def _install(recs: List[Dict[str, Any]], t: float, ver: Any = None) -> bool: | |
| exact: Dict[str, Dict[str, Any]] = {} | |
| loose: Dict[str, Dict[str, Any]] = {} | |
| for r in recs: | |
| try: | |
| sc = float(r["score"]) | |
| except (KeyError, TypeError, ValueError): | |
| continue # null=沒測,不算 0 | |
| rec = {"name": r.get("name") or r.get("slug") or "", "slug": r.get("slug") or "", "score": sc} | |
| for nm in {r.get("slug") or "", r.get("name") or ""}: | |
| nk = _norm(nm) | |
| if nk and (nk not in exact or sc > exact[nk]["score"]): | |
| exact[nk] = rec | |
| lk = _loose(nm) | |
| if lk and (lk not in loose or sc > loose[lk]["score"]): | |
| loose[lk] = rec | |
| if not exact: | |
| return False | |
| vals = sorted({id(v): v["score"] for v in exact.values()}.values()) | |
| cut = vals[min(len(vals) - 1, int(len(vals) * FLAGSHIP_PCT))] if vals else None | |
| with _LOCK: | |
| _S.update(exact=exact, loose=loose, ver=ver, n=len({id(v) for v in exact.values()}), at=t, err="", cut=cut) | |
| return True | |
| def dumps() -> str: | |
| with _LOCK: | |
| seen, rows = set(), [] | |
| for r in _S["exact"].values(): | |
| if id(r) in seen: | |
| continue | |
| seen.add(id(r)) | |
| rows.append({"name": r["name"], "slug": r["slug"], "score": round(r["score"], 2)}) | |
| return json.dumps({"v": 1, "ver": _S["ver"], "at": _S["at"], "rows": rows}, ensure_ascii=False, separators=(",", ":")) | |
| def load_saved() -> bool: | |
| fn = _CFG.get("load") | |
| if fn is None or _S["exact"]: | |
| return False | |
| try: | |
| d = json.loads(fn() or "{}") | |
| ok = _install(list(d.get("rows") or []), float(d.get("at") or time.time()), d.get("ver")) | |
| except Exception: | |
| return False | |
| if ok: | |
| _S["from_store"] = True | |
| return ok | |
| def lookup(model_id: str) -> Optional[Dict[str, Any]]: | |
| """模型 ID → {"score", "name", "exact"};AA 上沒有回 None。""" | |
| n = _norm(model_id) | |
| if not n: | |
| return None | |
| with _LOCK: | |
| rec = _S["exact"].get(n) | |
| if rec is not None: | |
| return dict(rec, exact=True) | |
| lk = _loose(n) | |
| rec = _S["exact"].get(lk) or _S["loose"].get(lk) | |
| if rec is None: | |
| sk = _strip_size(lk) | |
| if sk != lk: | |
| rec = _S["exact"].get(sk) | |
| return dict(rec, exact=False) if rec is not None else None | |
| def score(model_id: str) -> Optional[float]: | |
| r = lookup(model_id) | |
| return r["score"] if r else None | |
| def label(model_id: str) -> str: | |
| """「AA 52」「AA ≈52」(版本尾巴不同);沒有分數回「AA —」。""" | |
| r = lookup(model_id) | |
| if not r: | |
| return "AA —" | |
| return "AA %s%.0f" % ("" if r["exact"] else "≈", r["score"]) | |
| def compare(a: Optional[float], b: Optional[float]) -> str: | |
| if a is None or b is None: | |
| return "" | |
| d = a - b | |
| if abs(d) < TIE: | |
| return "差不多" | |
| return ("+%.0f" % d) if d > 0 else ("−%.0f" % -d) | |
| def tier_of(model_id: str) -> Optional[str]: | |
| """內部分級(不顯示):有分數 → 前 40% 算「旗艦」、其餘「輕量」;沒分數回 None(呼叫端照名稱分)。""" | |
| s, cut = score(model_id), _S.get("cut") | |
| if s is None or cut is None: | |
| return None | |
| return "旗艦" if s >= cut else "輕量" | |
| def near(model_id: str, n: int = 3) -> List[Dict[str, Any]]: | |
| """AA 上名字最像的幾支(對不上時給人看 AA 怎麼叫它):照名字片段重疊多寡排。""" | |
| want = set(_norm(model_id).split("-")) - {""} | |
| if not want: | |
| return [] | |
| with _LOCK: | |
| recs = {id(r): r for r in _S["exact"].values()}.values() | |
| scored = [] | |
| for r in recs: | |
| toks = set(_norm(r["slug"] or r["name"]).split("-")) | set(_norm(r["name"]).split("-")) | |
| toks.discard("") | |
| inter = len(want & toks) | |
| if inter: | |
| scored.append((inter / len(want | toks), r)) | |
| scored.sort(key=lambda x: -x[0]) | |
| return [dict(r) for _s, r in scored[:n]] | |
| def match_line(model_id: str) -> str: | |
| """★2026-11-24 主人「都沒有 已經設金鑰了」:/health 看每個位置的模型對到 AA 的哪一支、沒對到的話 AA 上相近的叫什麼。""" | |
| short = str(model_id).rsplit("/", 1)[-1] | |
| r = lookup(model_id) | |
| if r: | |
| return "%s → %s(AA 上叫 %s)" % (short, label(model_id), r["name"]) | |
| if not _S["exact"]: | |
| return "%s → 還沒抓到 AA" % short | |
| nb = near(model_id) | |
| return "%s → 沒對上%s" % (short, (";AA 上相近:" + "、".join("%s(%s,%.0f)" % (x["name"], x["slug"], x["score"]) for x in nb)) | |
| if nb else ";AA 上沒有名字相近的") | |
| def loaded() -> bool: | |
| return bool(_S["exact"]) | |
| def version() -> Any: | |
| return _S["ver"] | |
| def start(first_delay: float = FIRST_DELAY, log: Callable[[str], None] = lambda s: print(s, flush=True)) -> bool: | |
| if _S["thread"]: | |
| return False | |
| _S["thread"] = True | |
| def _loop() -> None: | |
| try: | |
| if load_saved(): | |
| log("[AA] 先用上次存的:%d 支(第 %s 版指數)" % (_S["n"], _S["ver"])) | |
| except Exception: # pragma: no cover | |
| pass | |
| time.sleep(first_delay) | |
| while True: | |
| ok = False | |
| try: | |
| ok = fetch() | |
| except Exception as e: # pragma: no cover | |
| _S["err"] = type(e).__name__ | |
| if ok: | |
| log("[AA] 抓到 %d 支(第 %s 版指數)" % (_S["n"], _S["ver"])) | |
| elif _S["err"] == "沒設 AA_API_KEY": | |
| log("[AA] 沒設 AA_API_KEY → /model 先顯示「AA —」,明天再看一次") | |
| else: | |
| log("[AA] 抓取失敗:%s,%d 小時後再試" % (_S["err"], RETRY_S // 3600)) | |
| time.sleep(REFRESH_S if ok or _S["err"] == "沒設 AA_API_KEY" else RETRY_S) | |
| threading.Thread(target=_loop, daemon=True, name="vb_aa").start() | |
| return True | |
| def line(now: Optional[float] = None) -> str: | |
| t = time.time() if now is None else now | |
| if not _S["exact"]: | |
| base = "AA 智力指數(/model 排序):還沒抓到" | |
| else: | |
| base = "AA 智力指數(/model 排序):第 %s 版、%d 支;%.0f 小時前抓的%s" % ( | |
| _S["ver"] or "?", _S["n"], (t - _S["at"]) / 3600.0, "(開機讀回的存檔)" if _S["from_store"] and not _S["n_ok"] else "") | |
| return base + ";抓取 成功 %d 失敗 %d%s" % (_S["n_ok"], _S["n_fail"], (";最近錯誤 " + _S["err"]) if _S["err"] else "") | |
| def reset() -> None: | |
| with _LOCK: | |
| _S.update(exact={}, loose={}, ver=None, n=0, at=None, n_ok=0, n_fail=0, err="", from_store=False, cut=None) | |
| _CFG.update(load=None, save=None, key=None) | |