Spaces:
Running
Running
Download vb_models.py from jay0826/discord-bot: direct link, hf CLI and curl.
- Browser
- Download file 23.8 kB
-
https://huggingface.co/spaces/jay0826/discord-bot/resolve/main/vb_models.py
- Command line
-
hf download hf://spaces/jay0826/discord-bot/vb_models.py
-
curl -L -o vb_models.py https://huggingface.co/spaces/jay0826/discord-bot/resolve/main/vb_models.py
23.8 kB
| # -*- coding: utf-8 -*- | |
| """模型清單檢查:每個供應商用 Space 自己的金鑰列一次模型,回答三件事。 | |
| ① 金鑰還有效嗎(列得出來=有效;401/403=無效或過期) | |
| ② 設定裡用的模型還在清單上嗎(不在=可能已下架,會靜默降級) | |
| ③ 同系列有沒有更新的版本(gemini-3.6-flash 在用,清單上有 3.8-flash → 提示) | |
| ★只**偵測與提示**,不自動切換。新版的免費額度、風格、拒答行為都可能不同, | |
| 換不換該由主人決定;換的動作是改一個環境變數,不用動程式。 | |
| ★成本:列清單不吃生成額度。z.ai 這種不支援列清單的端點,退回對每個設定的模型 | |
| 打 1 個 token 的請求(一天一次,免費模型零成本)。 | |
| 供應商設定由 discordbot 注入(`set_providers`),這個檔不碰金鑰、不讀環境變數, | |
| 所以可以直接測。 | |
| """ | |
| import concurrent.futures as _fut | |
| import re | |
| import threading | |
| import time | |
| from typing import Any, Callable, Dict, List, Optional, Tuple | |
| Lister = Callable[[], List[str]] | |
| Pulser = Callable[[str], int] | |
| class ListError(Exception): | |
| """列清單失敗;`status` 是 HTTP 狀態碼(沒有就 0)。""" | |
| def __init__(self, msg: str, status: int = 0): | |
| super().__init__(msg) | |
| self.status = status | |
| # ── 取清單的兩種通用做法(requests 由呼叫端注入,可測) ──────────────── | |
| def openai_models(base: str, key: Optional[str], get: Callable[..., Any], | |
| timeout: int = 15) -> List[str]: | |
| """OpenAI 相容的 GET {base}/models → [id, ...]。""" | |
| r = get(base.rstrip("/") + "/models", headers={"Authorization": "Bearer %s" % (key or "")}, | |
| timeout=timeout) | |
| code = int(getattr(r, "status_code", 0) or 0) | |
| if code != 200: | |
| raise ListError("HTTP %d" % code, code) | |
| body = r.json() or {} | |
| data = body.get("data") if isinstance(body, dict) else body | |
| if not isinstance(data, list): | |
| raise ListError("回應裡沒有 data 陣列", 200) | |
| return [str(x.get("id") or x.get("name") or "") for x in data if isinstance(x, dict)] | |
| def pulse(base: str, key: Optional[str], model: str, post: Callable[..., Any], | |
| timeout: int = 20) -> int: | |
| """1 個 token 的聊天請求,只看 HTTP 狀態。""" | |
| r = post(base.rstrip("/") + "/chat/completions", | |
| headers={"Authorization": "Bearer %s" % (key or ""), "Content-Type": "application/json"}, | |
| json={"model": model, "max_tokens": 1, "messages": [{"role": "user", "content": "hi"}]}, | |
| timeout=timeout) | |
| return int(getattr(r, "status_code", 0) or 0) | |
| # ── 版號比較 ────────────────────────────────────────────────────── | |
| _ID = re.compile(r"^([a-z][a-z-]*?)-?(\d+(?:\.\d+)*)(.*)$") | |
| def norm_id(model_id: str) -> str: | |
| """去掉供應商前綴:models/gemini-x、z-ai/glm-x、meta-llama/llama-x。""" | |
| s = (model_id or "").strip() | |
| if "/" in s: | |
| s = s.rsplit("/", 1)[1] | |
| return s.lower() | |
| def parse_id(model_id: str) -> Optional[Tuple[str, Tuple[int, ...], str]]: | |
| """'gemini-3.8-flash' → ('gemini', (3, 8), 'flash');沒有版號回 None。""" | |
| m = _ID.match(norm_id(model_id)) | |
| if not m: | |
| return None | |
| fam, ver, rest = m.group(1), m.group(2), m.group(3) | |
| # ★「gpt-oss-120b」的 120 是參數量不是版號——2026-09-06 實測把 20b → 120b 報成「較新」。 | |
| # 數字後面緊接 b(且之後是結尾、- 或 :)就當作大小,不比版本。 | |
| if rest.startswith("b") and (len(rest) == 1 or rest[1] in "-:"): | |
| return None | |
| try: | |
| vt = tuple(int(x) for x in ver.split(".")) | |
| except ValueError: | |
| return None | |
| return fam, vt, rest.lstrip("-") | |
| # ★2026-09-21 主人問「是怎麼偵測有沒有新模型的」,實測出兩個盲點: | |
| # · 名稱帶快照日期的(NIM 的 deepseek-v4-flash-0731):日期被當成變體的一部分,下一版日期一定不同 → 永遠比不到; | |
| # 同版號只換日期的(…-0915)也看不到。偏偏這就是當時壞掉、最需要換的那個位置。 | |
| # · 換了參數量的(qwen3.8-27b → qwen4-32b):27b/32b 被當成不同變體。 | |
| # 做法:比對前把「日期」與「參數量」從變體裡拆出來,剩下的核心變體(flash、flash-lite、coder:free…)相同才比; | |
| # 拆掉的東西不同就在結果上加註(日期較新/尺寸不同),不假裝它們是同一支。preview、tts、image 這種仍然是不同變體、不算。 | |
| _DATE_TOK = re.compile(r"^(?:\d{4}|\d{6}|\d{8})$") # 0731、250731、20250731 | |
| _SIZE_TOK = re.compile(r"^a?\d+(?:\.\d+)?b$") # 27b、120b、a22b(MoE 的啟用參數) | |
| _SIZE_NUM = re.compile(r"(?:^|[-_/])a?(\d+(?:\.\d+)?)b(?=$|[-_:])") | |
| LIGHT_WORDS = ("lite", "mini", "nano", "small", "tiny", "haiku", "instant", "edge") | |
| LIGHT_MAX_B = 60.0 # 參數量小於這個(十億)算輕量;沒寫參數量、名字也沒有輕量字樣的算旗艦 | |
| def split_variant(var: str) -> Tuple[str, str, str]: | |
| """變體 →(核心變體, 日期, 尺寸)。'flash-0731' → ('flash', '0731', '');'27b' → ('', '', '27b');'coder:free' 不動。""" | |
| head, _sep, tail = (var or "").partition(":") | |
| core, date, size = [], "", "" | |
| for tok in [t for t in head.split("-") if t]: | |
| if _DATE_TOK.match(tok) and not date: | |
| date = tok | |
| elif _SIZE_TOK.match(tok) and not size: | |
| size = tok | |
| else: | |
| core.append(tok) | |
| return "-".join(core) + ((":" + tail) if tail else ""), date, size | |
| def newer_detail(model_id: str, available: List[str]) -> List[Tuple[str, str]]: | |
| """[(模型, 加註)],新→舊。同系列、同核心變體,而且(版號更高)或(同版號、同格式的日期更晚)。 | |
| 加註:'' /'日期較新'/'尺寸不同'/'日期較新、尺寸不同'。MMDD 沒有年份,跨年(1215 → 0110)比不出來——寧可漏報不要亂報。""" | |
| me = parse_id(model_id) | |
| if not me: | |
| return [] | |
| fam, ver, var = me | |
| core, date, size = split_variant(var) | |
| out = [] | |
| for a in available: | |
| p = parse_id(a) | |
| if not p or p[0] != fam: | |
| continue | |
| c2, d2, s2 = split_variant(p[2]) | |
| if c2 != core: | |
| continue | |
| notes = [] | |
| if p[1] > ver: | |
| pass | |
| elif p[1] == ver and date and d2 and len(d2) == len(date) and d2 > date: | |
| notes.append("日期較新") | |
| else: | |
| continue | |
| if s2 != size: | |
| notes.append("尺寸不同") | |
| out.append((p[1], d2, norm_id(a), "、".join(notes))) | |
| seen, res = set(), [] | |
| for _v, _d, n, note in sorted(out, reverse=True): | |
| if n not in seen: | |
| seen.add(n) | |
| res.append((n, note)) | |
| return res | |
| def newer_than(model_id: str, available: List[str]) -> List[str]: | |
| """同系列、同核心變體、比較新的清單(新→舊)。變體不同(preview、image、tts)不算;細節見 newer_detail。""" | |
| return [n for n, _note in newer_detail(model_id, available)] | |
| def tier_of(model_id: str) -> str: | |
| """依**名稱**粗分「旗艦/輕量」(給週報與換模型的候選清單排序用;不是能力評測): | |
| 名字有 lite/mini/nano…,或寫了參數量且小於 LIGHT_MAX_B → 輕量;其餘(含沒寫參數量的 flash、pro、v4…)→ 旗艦。""" | |
| s = norm_id(model_id) | |
| toks = re.split(r"[-_:.]", s) | |
| if any(w in toks for w in LIGHT_WORDS): | |
| return "輕量" | |
| sizes = [float(x) for x in _SIZE_NUM.findall(s)] | |
| if sizes: | |
| return "輕量" if max(sizes) < LIGHT_MAX_B else "旗艦" | |
| return "旗艦" | |
| def status_word(st: Optional[int]) -> str: | |
| """實際呼叫的狀態碼 → 一句話。★429 是「存在但被限流」,不是下架——第一版全寫成已下架,錯。""" | |
| if st == 200: | |
| return "可呼叫" | |
| if st in (404, 410): | |
| return "已下架" | |
| if st == 429: | |
| return "存在但被限流(免費額度可能用盡)" | |
| if st in (401, 403): | |
| return "沒權限(金鑰或方案)" | |
| if st == 400: | |
| return "被拒(模型名可能已改)" | |
| if st is None or st < 0: | |
| return "呼叫本身失敗(逾時或連不上)" | |
| return "HTTP %s" % st | |
| def alternatives(model_id: str, available: List[str], limit: int = 5) -> List[str]: | |
| """設定的模型不在時,同系列(任何變體)還有哪些可選,新→舊。""" | |
| me = parse_id(model_id) | |
| if not me: | |
| return [] | |
| fam = me[0] | |
| want_free = ":free" in me[2] # OpenRouter 的 :free 變體:設定的是免費,替代也先列免費 | |
| out = [] | |
| for a in available: | |
| p = parse_id(a) | |
| if p and p[0] == fam: | |
| out.append((0 if (want_free and ":free" in p[2]) else 1, p[1], norm_id(a))) | |
| # 免費優先 → 版號新→舊 → 同版號名字倒序(穩定排序疊兩次) | |
| out.sort(key=lambda x: x[2], reverse=True) | |
| out.sort(key=lambda x: (x[0], [-i for i in x[1]])) | |
| seen, res = set(), [] | |
| for _tier, _v, n in out: | |
| if n not in seen: | |
| seen.add(n) | |
| res.append(n) | |
| return res[:limit] | |
| # ★2026-09-22 主人截圖「為甚麼這麼少」:Gemini 的 /models 列 58 支,一半以上不是聊天模型(antigravity、deep-research、 | |
| # computer-use、native-audio、aqa、imagen、embedding…),NIM 的 82 支也混了嵌入、重排、語音、蛋白質。以前只擋七個關鍵字。 | |
| # Gemini 那邊 discordbot 已改用 API 回的 supported_actions(要有 generateContent)先過濾;這裡是名稱黑名單,給沒有能力資訊的供應商用。 | |
| _NOT_CHAT_SUB = ("whisper", "tts", "embed", "image", "transcribe", "veo", "lyria", "imagen", | |
| "deep-research", "computer-use", "native-audio", "antigravity", "robotics", | |
| "rerank", "retriev", "parakeet", "riva", "diffusion", "sdxl", "cosmos", "fastpitch", "ocr", "paddle", | |
| "segform", "molmim", "genmol", "diffdock", "alphafold", "proteinmpnn", "boltz", "evo2", "deepvariant", | |
| "nvclip", "dinov2", "studio-voice", "maxine", "audio2face", "safety", "guard", "esm2") | |
| _NOT_CHAT_TOK = {"aqa", "live", "clip", "esm", "vila", "neva", "fuyu", "kosmos"} | |
| def chat_like(model_id: str) -> bool: | |
| """能用 chat/completions 打 1 個 token、拿來當聊天模型的才算;語音、TTS、嵌入、重排、圖像、影片、視覺、科學模型都不算。""" | |
| s = norm_id(model_id) | |
| if any(k in s for k in _NOT_CHAT_SUB): | |
| return False | |
| return not any(t in _NOT_CHAT_TOK for t in re.split(r"[-_:.]", s)) | |
| def family_of(model_id: str) -> str: | |
| """系列名:'deepseek-ai/deepseek-v5-flash-1001' → 'deepseek-v'、'gpt-oss-120b' → 'gpt-oss'、'kimi-k3' → 'kimi-k'。""" | |
| p = parse_id(model_id) | |
| if p: | |
| return p[0] | |
| s = norm_id(model_id) | |
| m = re.match(r"^([a-z][a-z-]*?)-?\d", s) | |
| return (m.group(1) if m else s).rstrip("-") | |
| def rank_candidates(ids: List[str], default_model: str, want_tier: str = "") -> List[Tuple[str, str]]: | |
| """換模型的候選排序 → [(級別, 原始 ID)]:跟這個位置預設模型**同系列**的在前(同系列裡同級優先、版號新→舊), | |
| 其餘先同級(旗艦/輕量)再照原始 ID。不同系列之間不比版號(沒有意義)。Discord 自動完成只能列 25 項,排序決定主人看得到什麼。""" | |
| fam = family_of(default_model) | |
| rows = [] | |
| for i in ids: | |
| if not chat_like(i): | |
| continue | |
| same = family_of(i) == fam | |
| p = parse_id(i) | |
| ver = tuple(-v for v in p[1]) if (same and p) else (0,) | |
| t = tier_of(i) | |
| rows.append(((0 if same else 1), (0 if t == want_tier else 1), ver, i.lower(), t, i)) | |
| rows.sort() | |
| return [(t, i) for _f, _t, _v, _n, t, i in rows] | |
| def rank_by_score(ids: List[str], default_model: str, want_tier: str = "", | |
| score: Optional[Callable[[str], Optional[float]]] = None) -> List[Dict[str, Any]]: | |
| """★2026-09-23 主人(換模型清單):「你會不知道打誰,跟哪個模型能力較強」→ 有分數(LMArena 中文榜)的照分數高→低排前面, | |
| 沒分數的排後面、照 rank_candidates 原本的順序(同系列新→舊、同級、ID)。回 [{"id", "tier", "score"}]。""" | |
| base = rank_candidates(ids, default_model, want_tier) | |
| rows: List[Dict[str, Any]] = [] | |
| for k, (t, i) in enumerate(base): | |
| s = None | |
| if score is not None: | |
| try: | |
| s = score(i) | |
| except Exception: | |
| s = None | |
| rows.append({"id": i, "tier": t, "score": s, "_k": k}) | |
| rows.sort(key=lambda r: (r["score"] is None, -(r["score"] or 0.0), r["_k"])) | |
| for r in rows: | |
| r.pop("_k") | |
| # ★2026-09-28 主人:「他推薦 k2.6,明明有 k3」——沒分數的新版(中文榜還沒收、或名字對不上)以前一律沉到最後, | |
| # 舊版反而因為有分數排第一。改成:排在同系列、有分數的前一版正上方,記 prev/prev_score;前一版記 newer(呼叫端據此不推薦舊版)。 | |
| scored = [r for r in rows if r["score"] is not None] | |
| above: Dict[str, List[Dict[str, Any]]] = {} | |
| for r in rows: | |
| if r["score"] is not None: | |
| continue | |
| olds = [s for s in scored if newer_detail(s["id"], [r["id"]])] | |
| if not olds: | |
| continue | |
| p = max(olds, key=lambda s: (parse_id(s["id"]) or ("", (0,), ""))[1]) | |
| r["prev"], r["prev_score"] = p["id"], p["score"] | |
| p.setdefault("newer", []).append(r["id"]) | |
| above.setdefault(p["id"], []).append(r) | |
| out: List[Dict[str, Any]] = [] | |
| for r in rows: | |
| if r.get("prev"): | |
| continue | |
| out.extend(above.get(r["id"], [])) | |
| out.append(r) | |
| return out | |
| # ── 單一供應商 ──────────────────────────────────────────────────── | |
| def check(name: str, configured: List[str], lister: Optional[Lister], | |
| pulser: Optional[Pulser] = None, has_key: bool = True, | |
| keyname: str = "") -> Dict[str, Any]: | |
| res: Dict[str, Any] = {"name": name, "ok": False, "skipped": False, "err": "", | |
| "n": 0, "mode": "list", "models": []} | |
| if not has_key: | |
| res["skipped"] = True | |
| res["err"] = "沒設 %s,略過" % (keyname or "金鑰") | |
| return res | |
| avail: List[str] = [] | |
| try: | |
| if lister is None: | |
| raise ListError("沒有清單端點", 0) | |
| raw = [str(a) for a in lister()] | |
| avail = [norm_id(a) for a in raw] | |
| res["n"] = len(avail) | |
| res["avail"] = sorted(avail) | |
| # ★印給主人看的用**原始 ID**(含廠商前綴,如 deepseek-ai/…)——換模型要抄得走 | |
| res["avail_raw"] = sorted(a[7:] if a.startswith("models/") else a for a in raw) | |
| res["ok"] = True | |
| except ListError as e: | |
| if e.status in (404, 405) and pulser is not None: | |
| res["mode"] = "pulse" | |
| res["ok"] = True | |
| res["err"] = "清單端點不支援,改 1-token 測試" | |
| elif e.status in (401, 403): | |
| res["err"] = "HTTP %d(金鑰無效或過期)" % e.status | |
| return res | |
| else: | |
| res["err"] = str(e)[:80] | |
| return res | |
| except Exception as e: | |
| res["err"] = "%s: %s" % (type(e).__name__, str(e)[:60]) | |
| return res | |
| for cid in configured: | |
| if not cid: | |
| continue | |
| item = {"id": cid, "present": None, "newer": [], "status": None, "verified": False, | |
| "alts": []} | |
| if res["mode"] == "list": | |
| item["present"] = norm_id(cid) in avail | |
| # ★建議換的名字用**原始 ID**(2026-09-27:以前印 deepseek-v4.1-flash,照抄去 /admin swap 是 404——NIM 要 deepseek-ai/ 前綴) | |
| raw_of = {norm_id(a): (a[7:] if a.startswith("models/") else a) for a in raw} | |
| _nd = [(raw_of.get(n, n), note) for n, note in newer_detail(cid, avail)] | |
| item["newer"] = [n for n, _note in _nd] | |
| item["newer_note"] = {n: note for n, note in _nd if note} | |
| if not item["present"]: | |
| item["alts"] = [raw_of.get(n, n) for n in alternatives(cid, avail)] | |
| # ★清單沒列 ≠ 不能用(2026-09-06 實測:z.ai 的 /models 只列 10 支,沒有仍免費的 | |
| # glm-4.7-flash)。有 pulser 就再打 1 個 token 確認,只信實際呼叫的結果。 | |
| if item["present"] is False and pulser is not None and chat_like(cid): | |
| try: | |
| st = int(pulser(cid)) | |
| except Exception as e: | |
| st = -1 | |
| item["err"] = type(e).__name__ | |
| item["status"] = st | |
| item["present"] = (st == 200) | |
| item["verified"] = True | |
| else: | |
| try: | |
| st = int(pulser(cid)) # type: ignore[misc] | |
| except Exception as e: | |
| st = -1 | |
| item["err"] = type(e).__name__ | |
| item["status"] = st | |
| item["present"] = (st == 200) | |
| res["models"].append(item) | |
| return res | |
| # ── 全部供應商、快取、輸出 ──────────────────────────────────────── | |
| _providers: List[Dict[str, Any]] = [] | |
| _cache: Dict[str, Any] = {"at": 0.0, "results": []} | |
| _lock = threading.Lock() | |
| _provider_fn: Optional[Callable[[], List[Dict[str, Any]]]] = None | |
| def set_providers(providers) -> None: | |
| """給清單,或給「回清單的函式」(每次 refresh 重新問一次——/admin swap 換過模型後,每日檢查要盯新的那支)。""" | |
| global _providers, _provider_fn | |
| if callable(providers): | |
| _provider_fn, _providers = providers, [] | |
| else: | |
| _provider_fn, _providers = None, list(providers) | |
| def refresh(timeout: float = 40.0) -> List[Dict[str, Any]]: | |
| """並行檢查所有供應商,結果進快取並回傳。""" | |
| ps = list(_provider_fn()) if _provider_fn is not None else list(_providers) | |
| if not ps: | |
| return [] | |
| def _one(p): | |
| try: | |
| return check(p["name"], p.get("configured") or [], p.get("lister"), | |
| p.get("pulser"), p.get("has_key", True), p.get("keyname", "")) | |
| except Exception as e: # check() 自己會接,這是保險 | |
| return {"name": p.get("name", "?"), "ok": False, "skipped": False, | |
| "err": "%s: %s" % (type(e).__name__, str(e)[:60]), "n": 0, | |
| "mode": "list", "models": []} | |
| with _fut.ThreadPoolExecutor(max_workers=len(ps)) as ex: | |
| futs = [ex.submit(_one, p) for p in ps] | |
| out = [] | |
| for p, f in zip(ps, futs): | |
| try: | |
| out.append(f.result(timeout=timeout)) | |
| except Exception as e: | |
| out.append({"name": p.get("name", "?"), "ok": False, "skipped": False, | |
| "err": "逾時或例外:%s" % type(e).__name__, "n": 0, | |
| "mode": "list", "models": []}) | |
| with _lock: | |
| _cache["at"] = time.time() | |
| _cache["results"] = out | |
| return out | |
| def results() -> Tuple[float, List[Dict[str, Any]]]: | |
| with _lock: | |
| return _cache["at"], list(_cache["results"]) | |
| def dead() -> set: | |
| """每日檢查**實際呼叫證實**已下架(404/410)的 {(供應商名, 正規化模型名)}。 | |
| 只信驗證過的:清單沒列但沒驗、被限流、逾時都不算死。""" | |
| _at, res = results() | |
| out = set() | |
| for r in res: | |
| for m in r.get("models") or []: | |
| if m.get("present") is False and m.get("verified") and m.get("status") in (404, 410): | |
| out.add((r["name"], norm_id(m["id"]))) | |
| return out | |
| def is_dead(provider: str, model_id: str) -> bool: | |
| return (provider, norm_id(model_id)) in dead() | |
| def _fmt_model(m: Dict[str, Any]) -> str: | |
| if m.get("present") is None: | |
| return "%s ?" % m["id"] | |
| if not m["present"]: | |
| alts = (";同系列可選:" + "、".join(m["alts"])) if m.get("alts") else "" | |
| if m.get("verified"): | |
| return "%s ✗ 清單沒列、實際呼叫 HTTP %s(%s)%s" % ( | |
| m["id"], m["status"], status_word(m["status"]), alts) | |
| if m.get("status") is not None: | |
| return "%s ✗ HTTP %s(%s)%s" % (m["id"], m["status"], status_word(m["status"]), alts) | |
| return "%s ✗ 不在清單(未驗證,可能只是清單沒列)%s" % (m["id"], alts) | |
| s = "%s ✓" % m["id"] | |
| if m.get("verified"): | |
| s += "(清單沒列,但可呼叫)" | |
| if m.get("newer"): | |
| _nn = m.get("newer_note") or {} | |
| s += " → 較新:" + "、".join(n + (("(%s)" % _nn[n]) if _nn.get(n) else "") for n in m["newer"][:3]) | |
| return s | |
| def format_lines(res: List[Dict[str, Any]], at: float = 0.0, | |
| now: Optional[float] = None) -> List[str]: | |
| if not res: | |
| return ["模型清單檢查:還沒跑過(開機 2.5 分鐘後第一次,之後每天一次)"] | |
| t = time.time() if now is None else now | |
| age = (t - at) / 3600.0 if at else None | |
| out = ["模型清單檢查(用 Space 自己的金鑰;每天一次%s;「較新」只看版號,額度與價格要自己確認)" | |
| % (",最近 %.1f 小時前" % age if age is not None else "")] | |
| upgrades = [] | |
| for r in res: | |
| if r.get("skipped"): | |
| out.append("- %s:%s" % (r["name"], r["err"])) | |
| continue | |
| if not r.get("ok"): | |
| out.append("✗ %s:%s" % (r["name"], r["err"])) | |
| continue | |
| head = ("%d 支" % r["n"]) if r.get("mode") == "list" else "1-token 測試" | |
| out.append("✓ %s:%s|%s" % (r["name"], head, | |
| "|".join(_fmt_model(m) for m in r["models"]) or "(沒有設定的模型)")) | |
| # ★有缺而且清單不長時把整份清單印出來——換模型要有得挑,不用再去翻文件 | |
| if r.get("avail") and any(m.get("present") is False for m in r["models"]) and len(r["avail"]) <= 100: | |
| out.append(" 清單:" + "、".join(r.get("avail_raw") or r["avail"])) | |
| for m in r["models"]: | |
| if m.get("newer"): | |
| upgrades.append("%s %s → %s" % (r["name"], m["id"], m["newer"][0])) | |
| out.append(" 有更新可換:" + ";".join(upgrades) if upgrades else " 沒有更新可換") | |
| return out | |
| def lines(now: Optional[float] = None) -> List[str]: | |
| at, res = results() | |
| return format_lines(res, at, now) | |
| def boot(printer: Callable[[str], None] = print, delay: float = 150.0, | |
| every: float = 86400.0) -> None: | |
| """開機後 delay 秒第一次,之後每 every 秒一次;結果印到 log 並留在快取給 /health。""" | |
| def _run(): | |
| time.sleep(delay) | |
| while True: | |
| try: | |
| refresh() | |
| for ln in lines(): | |
| printer("[模型清單] " + ln) | |
| except Exception as e: | |
| printer("[模型清單] 檢查本身失敗:%s: %s" % (type(e).__name__, str(e)[:60])) | |
| time.sleep(every) | |
| threading.Thread(target=_run, name="model-list-check", daemon=True).start() | |