Spaces:
Running
Running
Download vb_osu_api.py from jay0826/discord-bot: direct link, hf CLI and curl.
- Browser
- Download file 40 kB
-
https://huggingface.co/spaces/jay0826/discord-bot/resolve/main/vb_osu_api.py
- Command line
-
hf download hf://spaces/jay0826/discord-bot/vb_osu_api.py
-
curl -L -o vb_osu_api.py https://huggingface.co/spaces/jay0826/discord-bot/resolve/main/vb_osu_api.py
40 kB
| # -*- coding: utf-8 -*- | |
| """osu! API v2 的薄包裝(ossapi,client credentials)+ .osu 圖譜檔快取。 | |
| ★只讀公開資料:玩家資訊、top 成績、排行榜、圖譜。不碰遊戲客戶端、不自動打圖。 | |
| ★金鑰:OSU_CLIENT_ID/OSU_CLIENT_SECRET 只從環境變數讀,這裡不印、不存。 | |
| ★節流(★2026-10-09 改回守規):官方 API 文件 Terms of Use 寫「Please limit your usage to no more than 60 requests per minute | |
| (generally 1 request per second)」,內部上限較高、允許短暫突發,但超過這個規範「may lead to your API tokens being revoked」 | |
| (2026-09-10 那次放寬到 0.2 秒=300/分鐘是誤讀:1,200/分鐘是內部上限,不是使用規範)。主人 2026-10-09「允許存」→ | |
| 這裡每個請求之間至少隔 PACE 秒(預設 1.0=每分鐘 60 次),慢下來的部分用長時間快取補(難度屬性存到下次 pp 改版、 | |
| 圖譜資料 30 天、同儕 top 榜 7 天)。碰到 429 就把間隔加倍(3 秒冷卻)再重試一次,成功一陣子再放回來(不低於 PACE)。 | |
| 環境變數 OSU_PACE 可調,但**不要調到 1.0 以下**。 | |
| ★快取兩層(2026-09-10):磁碟(Space 重開就沒)+ Supabase `osu_cache`(跨重啟;DDL 在 SUPABASE_SETUP.md)。 | |
| 同儕的 top 榜、難度屬性、圖譜資料都是「一次算好、之後大家共用」的東西,第二天第一個查的人不該再等一分鐘。 | |
| 讀:磁碟沒有 → 一次把一整批 key 從 Supabase 撈回來寫進磁碟(cache_get_many);寫:磁碟+背景批次 upsert。 | |
| ★.osu 檔從 https://osu.ppy.sh/osu/{id} 下載(公開、不用金鑰),存 data/osu/ 重用。 | |
| """ | |
| import datetime as _dt | |
| import hashlib | |
| import json | |
| import os | |
| import queue | |
| import threading | |
| import time | |
| from typing import Any, Dict, List, Optional, Tuple | |
| import requests | |
| PACE = float(os.environ.get("OSU_PACE", "1.0") or 1.0) # ★2026-10-09 官方規範 ≤ 60/分鐘(約每秒 1 個) | |
| MAX_PACE = 4.0 # 429 時最多慢到 4 秒一個(一定要 ≥ PACE,不然加倍反而變快) | |
| _PACE_LOCK = threading.Lock() # ★整個行程共用的節流(所有 Client 一起排隊) | |
| _PACE_LAST = [0.0] | |
| API_VERSION = 20241024 # 原始端點要帶 x-api-version 才是新格式(mods 物件、statistics 的 great/ok/meh);跟 ossapi 5.3 預設同 | |
| SLOW_COOLDOWN = 3.0 # 429 之後幾秒內再碰到 429 不再加倍(8 條執行緒同時吃到 429 只能算一次) | |
| RECOVER_EVERY = 40 # 連續成功這麼多次就把間隔除以 1.5(不低於 PACE) | |
| OSU_FILE_URL = "https://osu.ppy.sh/osu/%d" | |
| CACHE_DIR = os.environ.get("VB_OSU_DIR", os.path.join("data", "osu")) | |
| RANK_PAGE = 50 # 排行榜每頁 50 人 | |
| RANK_MAX_PAGE = 200 # API 只給到第 200 頁(前 10,000 名) | |
| # ── 磁碟快取(2026-09-07:主人要求縮短等待)── | |
| # 難度屬性與圖譜資料只在官方改版才變,各存 7 天;top 榜由呼叫端決定 TTL(vb_osu_farm.fetch_best)。 | |
| # 第二次查(同一人換模式、朋友查、edge 接著 farm)大部分請求都不用再打 API。 | |
| # ★2026-10-09 主人「允許存」:難度屬性同一張圖、同一組 mods 在公式沒改之前不會變 → 存一年,key 帶公式版本(ATTR_VER), | |
| # pp 改版時把 ATTR_VER 改成 ppy/osu OsuDifficultyCalculator.Version 的新值,舊的就自然不讀了。圖譜資料(AR/OD、物件數、 | |
| # ranked 狀態、全站次數)30 天:全站次數只拿來排人氣,慢一點沒關係。 | |
| ATTR_VER = "20260706" | |
| CACHE_TTL_ATTR = 365 * 86400 | |
| CACHE_TTL_INFO = 30 * 86400 | |
| CACHE_TTL_PLAYED = 3600 # 你自己「打過幾次」的清單(most_played):1 小時(剛打的要看得到) | |
| CACHE_TTL_UBEST = 3 * 86400 # ★2026-10-08 /osu backtest:你在某張圖的最佳成績;只存磁碟。2026-10-09 守 60/分鐘 → 6 小時延長到 3 天 | |
| CACHE_TTL_UALL = 6 * 3600 # 你在某張圖的全部成績(/osu curve、backtest 手感):6 小時(剛打的要看得到) | |
| MOST_PLAYED_PAGES = 5 # most_played 每頁 100 張、依次數遞減;只抓前幾頁(後面都是打過一兩次的) | |
| CACHE_TTL_SRCH = 30 * 86400 # ★2026-10-10 能力區域候選索引(vb_osu_index):圖譜搜尋每頁結果 30 天(OSU_RESEARCH.md §8.1 第 7 點) | |
| RECENT_TTL = 120 # ★2026-10-10 今天狀態用的 recent:只放記憶體 2 分鐘(只讀不存,不進磁碟、不進 Supabase) | |
| SEARCH_URL = "https://osu.ppy.sh/api/v2/beatmapsets/search" | |
| def cache_get(cache_dir: Optional[str], kind: str, key: str, ttl: float) -> Any: | |
| """讀 JSON 快取;沒有、過期、壞掉都回 None。""" | |
| if not cache_dir or ttl <= 0: | |
| return None | |
| p = os.path.join(cache_dir, "cache", kind, key + ".json") | |
| try: | |
| if time.time() - os.path.getmtime(p) > ttl: | |
| return None | |
| with open(p, encoding="utf-8") as f: | |
| return json.load(f) | |
| except (OSError, ValueError): | |
| return None | |
| def _disk_put(cache_dir: Optional[str], kind: str, key: str, data: Any) -> None: | |
| if not cache_dir: | |
| return | |
| d = os.path.join(cache_dir, "cache", kind) | |
| try: | |
| os.makedirs(d, exist_ok=True) | |
| tmp = os.path.join(d, "%s.%d.tmp" % (key, threading.get_ident())) | |
| with open(tmp, "w", encoding="utf-8") as f: | |
| json.dump(data, f, ensure_ascii=False) | |
| os.replace(tmp, os.path.join(d, key + ".json")) | |
| except (OSError, TypeError, ValueError): | |
| pass # 快取寫不進去不該讓功能壞掉 | |
| def cache_put(cache_dir: Optional[str], kind: str, key: str, data: Any) -> None: | |
| """寫磁碟,並排進 Supabase 的背景寫入佇列(有設定才會寫)。""" | |
| _disk_put(cache_dir, kind, key, data) | |
| _sb_enqueue(kind, key, data) | |
| # ── 第二層:Supabase osu_cache(跨重啟;沒設定就全部略過) ────────────────── | |
| SB_TABLE = "osu_cache" | |
| SB_BATCH = 50 | |
| _SB: Dict[str, Any] = {"url": "", "key": "", "get": None, "post": None, "q": None, "thread": None, | |
| "writes": 0, "write_err": 0, "reads": 0, "read_err": 0, "hits": 0, "last_err": ""} | |
| _SB_LOCK = threading.Lock() | |
| def configure_cache(url: str = "", key: str = "", get=None, post=None) -> None: | |
| """設定 Supabase 第二層快取;url/key 空=關掉。get/post 可注入(測試)。""" | |
| with _SB_LOCK: | |
| _SB.update(url=(url or "").rstrip("/"), key=key or "", get=get, post=post, autoconf=True) | |
| if _SB["q"] is None: | |
| _SB["q"] = queue.Queue() | |
| def sb_on() -> bool: | |
| if not _SB["url"] and not _SB.get("autoconf"): | |
| # ★第一次問就從環境變數帶(跟 bot 同一組 Supabase);沒設就維持關閉。/health 在還沒人查 /osu 時也看得到狀態。 | |
| _SB["autoconf"] = True | |
| u, k = os.getenv("SUPABASE_URL", ""), (os.getenv("SUPABASE_SERVICE_KEY") or os.getenv("SUPABASE_KEY", "")) | |
| if u and k: | |
| configure_cache(u, k) | |
| return bool(_SB["url"] and _SB["key"]) | |
| def _sb_headers() -> Dict[str, str]: | |
| return {"apikey": _SB["key"], "Authorization": "Bearer " + _SB["key"], "Content-Type": "application/json", | |
| "User-Agent": "vanilla-bot osu cache/1.0"} | |
| def _sb_get(kind: str, keys: List[str], ttl: float) -> Dict[str, Any]: | |
| """一次撈一批 key(≤SB_BATCH 個一段);只要沒過期的。讀失敗回空(磁碟沒有就去打 API,跟以前一樣)。 | |
| ★2026-10-09 100 → 50:一位同儕 top 榜約 52 KB,100 位一次回 5 MB;Supabase 免費機記憶體很緊(主人截圖 swap 常駐 600 MB)。""" | |
| if not sb_on() or not keys: | |
| return {} | |
| get = _SB["get"] or requests.get | |
| since = _dt.datetime.fromtimestamp(time.time() - ttl, _dt.timezone.utc).isoformat() | |
| out: Dict[str, Any] = {} | |
| for i in range(0, len(keys), SB_BATCH): | |
| part = keys[i:i + SB_BATCH] | |
| try: | |
| r = get("%s/rest/v1/%s" % (_SB["url"], SB_TABLE), headers=_sb_headers(), timeout=20, | |
| params={"select": "key,val", "kind": "eq." + kind, "at": "gte." + since, | |
| "key": "in.(%s)" % ",".join('"%s"' % k for k in part)}) | |
| if r.status_code != 200: | |
| raise RuntimeError("HTTP %d %s" % (r.status_code, str(getattr(r, "text", ""))[:80])) | |
| for row in r.json() or []: | |
| out[str(row["key"])] = row["val"] | |
| _SB["reads"] += 1 | |
| except Exception as e: | |
| _SB["read_err"] += 1 | |
| _SB["last_err"] = "%s: %s" % (type(e).__name__, str(e)[:80]) | |
| try: | |
| import vb_quiet as Q | |
| Q.quiet("osu_cache.read", e) | |
| except Exception: | |
| pass | |
| _SB["hits"] += len(out) | |
| return out | |
| def _sb_writer() -> None: | |
| q = _SB["q"] | |
| while True: | |
| rows = [q.get()] | |
| try: | |
| while len(rows) < SB_BATCH: | |
| rows.append(q.get_nowait()) | |
| except queue.Empty: | |
| pass | |
| if not sb_on(): | |
| continue | |
| post = _SB["post"] or requests.post | |
| try: | |
| r = post("%s/rest/v1/%s" % (_SB["url"], SB_TABLE), json=rows, timeout=30, | |
| headers={**_sb_headers(), "Prefer": "resolution=merge-duplicates,return=minimal"}) | |
| if r.status_code not in (200, 201, 204): | |
| raise RuntimeError("HTTP %d %s" % (r.status_code, str(getattr(r, "text", ""))[:80])) | |
| _SB["writes"] += len(rows) | |
| except Exception as e: | |
| _SB["write_err"] += len(rows) | |
| _SB["last_err"] = "%s: %s" % (type(e).__name__, str(e)[:80]) | |
| try: | |
| import vb_quiet as Q | |
| Q.quiet("osu_cache.write", e) | |
| except Exception: | |
| pass | |
| for _ in rows: | |
| q.task_done() | |
| def _sb_enqueue(kind: str, key: str, data: Any) -> None: | |
| if not sb_on(): | |
| return | |
| with _SB_LOCK: | |
| if _SB["q"] is None: | |
| _SB["q"] = queue.Queue() | |
| if _SB["thread"] is None or not _SB["thread"].is_alive(): | |
| t = threading.Thread(target=_sb_writer, daemon=True, name="osu_cache") | |
| t.start() | |
| _SB["thread"] = t | |
| _SB["q"].put({"kind": kind, "key": key, "val": data, | |
| "at": _dt.datetime.now(_dt.timezone.utc).isoformat()}) | |
| def sb_flush(timeout: float = 5.0) -> None: | |
| """等背景寫完(測試與收工用)。""" | |
| q = _SB["q"] | |
| if q is None: | |
| return | |
| t0 = time.time() | |
| while not q.empty() and time.time() - t0 < timeout: | |
| time.sleep(0.02) | |
| time.sleep(0.05) | |
| def cache_get_many(cache_dir: Optional[str], kind: str, keys: List[str], ttl: float) -> Dict[str, Any]: | |
| """一批 key:磁碟有的直接用,沒有的一次去 Supabase 撈回來並寫進磁碟。回 {key: 資料}(沒有的不在裡面)。 | |
| ★這是提速的關鍵:250 位同儕的 top 榜以前要打 250 次 API,現在是一次資料庫查詢。""" | |
| out: Dict[str, Any] = {} | |
| miss: List[str] = [] | |
| for k in keys: | |
| v = cache_get(cache_dir, kind, k, ttl) | |
| if v is not None: | |
| out[k] = v | |
| else: | |
| miss.append(k) | |
| if miss and sb_on(): | |
| got = _sb_get(kind, miss, ttl) | |
| for k, v in got.items(): | |
| out[k] = v | |
| _disk_put(cache_dir, kind, k, v) | |
| return out | |
| def cache_line() -> str: | |
| on = sb_on() | |
| return "osu 快取(Supabase 第二層):%s;讀 %d 次命中 %d 筆(失敗 %d)、寫 %d 筆(失敗 %d)%s" % ( | |
| "有設定" if on else "未設定(只有磁碟,重開就沒)", _SB["reads"], _SB["hits"], _SB["read_err"], | |
| _SB["writes"], _SB["write_err"], (";最近錯誤 " + _SB["last_err"]) if _SB["last_err"] else "") | |
| def attr_key(beatmap_id: int, body: Dict[str, Any]) -> str: | |
| """難度屬性的快取 key:公式版本+圖+request body 的 md5(★2026-10-09 加 ATTR_VER:快取存一年,改版時換版本就不會讀到舊的)。""" | |
| return "%s_%d_%s" % (ATTR_VER, int(beatmap_id), hashlib.md5(json.dumps(body, sort_keys=True).encode()).hexdigest()[:10]) | |
| def attr_body(mods: Any = None) -> Dict[str, Any]: | |
| """attributes 端點的 request body(也是快取 key 的來源)。mods 給縮寫清單或帶 settings 的物件清單。""" | |
| body: Dict[str, Any] = {"ruleset": "osu"} | |
| if mods: | |
| out = [] | |
| for m in mods: | |
| if isinstance(m, str): | |
| out.append({"acronym": m.upper()}) | |
| elif isinstance(m, dict): | |
| d = {"acronym": str(m.get("acronym", "")).upper()} | |
| if m.get("settings"): | |
| d["settings"] = m["settings"] | |
| out.append(d) | |
| else: | |
| a = str(getattr(m, "acronym", "") or "").upper() | |
| if a: | |
| d = {"acronym": a} | |
| st = getattr(m, "settings", None) | |
| if isinstance(st, dict) and st: | |
| d["settings"] = st | |
| out.append(d) | |
| body["mods"] = out | |
| return body | |
| _RECENT: Dict[Tuple[int, bool, int], Tuple[float, List[dict]]] = {} # user_recent 的 2 分鐘記憶體快取(不落地) | |
| _RECENT_LOCK = threading.Lock() | |
| class Client: | |
| def __init__(self, client_id: str, client_secret: str, pace: float = PACE, | |
| cache_dir: str = CACHE_DIR): | |
| from ossapi import Ossapi | |
| self._api = Ossapi(int(client_id), client_secret) | |
| self._pace = float(pace) | |
| self._base = float(pace) | |
| self._last = 0.0 | |
| self._lock = threading.Lock() | |
| self.cache_dir = cache_dir | |
| def _wait(self) -> None: | |
| """★2026-10-10 節流改成整個行程共用(_PACE_LOCK/_PACE_LAST):每個 /osu 指令都 from_env() 開一個新的 Client, | |
| 以前各算各的,兩個指令同時跑就變每秒 2 個,超過官方 60/分鐘。間隔用這個 Client 的 _pace(429 退避時會變大)。""" | |
| with _PACE_LOCK: | |
| now = time.monotonic() | |
| gap = self._pace - (now - _PACE_LAST[0]) | |
| if gap > 0: | |
| time.sleep(gap) | |
| _PACE_LAST[0] = time.monotonic() | |
| self._last = _PACE_LAST[0] | |
| def _slow_down(self) -> float: | |
| """碰到 429:間隔加倍(上限 MAX_PACE),但 SLOW_COOLDOWN 秒內只加倍一次—— | |
| 2026-09-11 實跑:8 條執行緒同時吃到 429、各加倍一次,四步就到上限,之後 250 個請求全部 1 秒一個(同儕階段 187 秒)。 | |
| 回現在的間隔。""" | |
| with self._lock: | |
| now = time.monotonic() | |
| self._n429 = getattr(self, "_n429", 0) + 1 | |
| if now - getattr(self, "_slow_at", 0.0) >= SLOW_COOLDOWN: | |
| self._pace = min(MAX_PACE, max(self._pace * 2.0, 0.05)) | |
| self._slow_at = now | |
| self._ok_streak = 0 | |
| return self._pace | |
| def _ok(self) -> None: | |
| """成功一次;連續 RECOVER_EVERY 次沒有 429 就把間隔放回一點(不低於 PACE)。""" | |
| with self._lock: | |
| self._n_ok = getattr(self, "_n_ok", 0) + 1 | |
| self._ok_streak = getattr(self, "_ok_streak", 0) + 1 | |
| if self._ok_streak >= RECOVER_EVERY and self._pace > self._base: | |
| self._pace = max(self._base, self._pace / 1.5) | |
| self._ok_streak = 0 | |
| def stats(self) -> Dict[str, Any]: | |
| return {"ok": getattr(self, "_n_ok", 0), "n429": getattr(self, "_n429", 0), | |
| "pace": round(self._pace, 3), "base": self._base} | |
| def _call(self, fn, what: str): | |
| """打一次 API;429 就退避後再試一次(只試一次——再不行就讓呼叫端知道)。""" | |
| self._wait() | |
| try: | |
| r = fn() | |
| except Exception as e: | |
| if "429" not in str(e) and "Too Many" not in str(e): | |
| raise | |
| p = self._slow_down() | |
| time.sleep(max(1.5, p * 5)) | |
| self._wait() | |
| r = fn() | |
| self._ok() | |
| return r | |
| # ── 玩家 ────────────────────────────────────────────────────── | |
| def user(self, name_or_id: str) -> Optional[Any]: | |
| """回一個有 id/username/pp/global_rank/country_code/country_rank 的物件;找不到回 None。""" | |
| key = "id" if str(name_or_id).strip().isdigit() else "username" | |
| try: | |
| u = self._call(lambda: self._api.user(name_or_id, mode="osu", key=key), "user") | |
| except Exception as e: | |
| if "404" in str(e): | |
| return None | |
| raise | |
| st = getattr(u, "statistics", None) | |
| return _UserView( | |
| id=int(u.id), username=str(u.username), | |
| pp=float(getattr(st, "pp", 0.0) or 0.0), | |
| global_rank=getattr(st, "global_rank", None), | |
| country_rank=getattr(st, "country_rank", None), | |
| country_code=str(getattr(u, "country_code", "") or ""), | |
| play_count=getattr(st, "play_count", None)) # ★2026-10-10 vb_osu_track 的缺漏偵測用 | |
| def best(self, user_id: int, limit: int = 100) -> List[Any]: | |
| """top 榜。★直接拿原始 JSON(dict),不經 ossapi 的模型解析。 | |
| 2026-09-11 實跑:250 位同儕 240 秒、429 ×0、間隔 0.2 秒——瓶頸不是網路也不是節流,是 ossapi 把每筆成績 | |
| 轉成型別物件的 CPU(每人 100 筆約 0.8 秒;GIL 下 8 條執行緒等於沒有)。norm_score 本來就同時吃 dict 與物件。 | |
| 原始端點回非 200 或不是 list 就退回 ossapi(慢但一定對)。""" | |
| url = "https://osu.ppy.sh/api/v2/users/%d/scores/best" % int(user_id) | |
| def raw(): | |
| r = self._api.session.get(url, params={"mode": "osu", "limit": int(limit)}, | |
| headers={"x-api-version": str(API_VERSION)}, timeout=30) | |
| if r.status_code == 429: | |
| raise RuntimeError("429 Too Many Requests(best)") | |
| return r | |
| try: | |
| r = self._call(raw, "best") | |
| if r.status_code == 200: | |
| data = r.json() | |
| if isinstance(data, list): | |
| return data | |
| except Exception as e: | |
| if "429" in str(e): | |
| raise | |
| return list(self._call(lambda: self._api.user_scores(int(user_id), "best", mode="osu", limit=int(limit)), "best")) | |
| def most_played(self, user_id: int, pages: int = MOST_PLAYED_PAGES) -> Dict[int, int]: | |
| """你打過幾次:GET /users/{id}/beatmapsets/most_played(每頁 100、依次數遞減)→ {beatmap_id: 次數}。 | |
| ★2026-09-11 主人:「farm 真的應該強制考量遊玩次數」。只抓前 pages 頁;一小時快取(磁碟+Supabase)。 | |
| 原始 JSON;端點壞了退回 ossapi 的 user_beatmaps(type='most_played')。""" | |
| uid = int(user_id) | |
| key = str(uid) | |
| hit = cache_get(self.cache_dir, "played", key, CACHE_TTL_PLAYED) | |
| if isinstance(hit, dict): | |
| return {int(k): int(v) for k, v in hit.items()} | |
| out: Dict[int, int] = {} | |
| meta: Dict[str, Dict[str, str]] = {} | |
| url = "https://osu.ppy.sh/api/v2/users/%d/beatmapsets/most_played" % uid | |
| for page in range(int(pages)): | |
| params = {"limit": 100, "offset": page * 100} | |
| def raw(params=params): | |
| r = self._api.session.get(url, params=params, headers={"x-api-version": str(API_VERSION)}, timeout=30) | |
| if r.status_code == 429: | |
| raise RuntimeError("429 Too Many Requests(most_played)") | |
| return r | |
| rows: List[Any] | |
| try: | |
| r = self._call(raw, "most_played") | |
| data = r.json() if r.status_code == 200 else None | |
| if not isinstance(data, list): | |
| raise RuntimeError("most_played HTTP %d" % r.status_code) | |
| rows = data | |
| except Exception as e: | |
| if "429" in str(e): | |
| raise | |
| rows = list(self._call(lambda: self._api.user_beatmaps(uid, "most_played", limit=100, offset=page * 100), | |
| "most_played")) | |
| for it in rows: | |
| bid = it.get("beatmap_id") if isinstance(it, dict) else getattr(it, "beatmap_id", None) | |
| cnt = it.get("count") if isinstance(it, dict) else getattr(it, "count", None) | |
| if bid: | |
| out[int(bid)] = int(cnt or 0) | |
| m = _played_meta(it) | |
| if m: | |
| meta[str(int(bid))] = m | |
| if len(rows) < 100: | |
| break | |
| cache_put(self.cache_dir, "played", key, {str(k): v for k, v in out.items()}) | |
| if meta: | |
| cache_put(self.cache_dir, "pmeta", key, meta) | |
| return out | |
| def most_played_meta(self, user_id: int) -> Dict[int, Dict[str, str]]: | |
| """★2026-10-10 most_played 那幾頁附的圖名(title/artist/version/creator),{beatmap_id: {...}}。 | |
| 只讀 most_played() 存下的快取,**不打 API**;沒有就空的(/osu farm 會顯示 b/ID)。""" | |
| hit = cache_get(self.cache_dir, "pmeta", str(int(user_id)), CACHE_TTL_PLAYED) | |
| return {int(k): dict(v) for k, v in hit.items() if isinstance(v, dict)} if isinstance(hit, dict) else {} | |
| # ── 單圖成績(★2026-10-08 /osu backtest 用)────────────────────── | |
| def user_beatmap_score(self, beatmap_id: int, user_id: int) -> Optional[dict]: | |
| """某人在某張圖的最好成績(GET /beatmaps/{id}/scores/users/{uid};沒過關過=404 → None)。回原始 JSON 的 score。 | |
| 沒有也記起來({"score": None}),回測不會對同一張一直問。""" | |
| bid, uid = int(beatmap_id), int(user_id) | |
| key = "%d_%d" % (uid, bid) | |
| hit = cache_get(self.cache_dir, "ubest", key, CACHE_TTL_UBEST) | |
| if isinstance(hit, dict) and "score" in hit: | |
| return hit["score"] | |
| url = "https://osu.ppy.sh/api/v2/beatmaps/%d/scores/users/%d" % (bid, uid) | |
| def raw(): | |
| r = self._api.session.get(url, params={"mode": "osu"}, headers={"x-api-version": str(API_VERSION)}, timeout=30) | |
| if r.status_code == 429: | |
| raise RuntimeError("429 Too Many Requests(user_beatmap_score)") | |
| return r | |
| r = self._call(raw, "user_beatmap_score") | |
| score = None | |
| if r.status_code == 200: | |
| data = r.json() | |
| score = data.get("score") if isinstance(data, dict) else None | |
| elif r.status_code != 404: | |
| raise RuntimeError("user_beatmap_score HTTP %d(b/%d)" % (r.status_code, bid)) | |
| _disk_put(self.cache_dir, "ubest", key, {"score": score}) | |
| return score | |
| def user_beatmap_scores_all(self, beatmap_id: int, user_id: int) -> List[dict]: | |
| """某人在某張圖的全部成績(GET …/scores/users/{uid}/all;lazer 時代的成績才有多筆,stable 只有最好的一筆或空)。""" | |
| bid, uid = int(beatmap_id), int(user_id) | |
| key = "%d_%d" % (uid, bid) | |
| hit = cache_get(self.cache_dir, "uall", key, CACHE_TTL_UALL) | |
| if isinstance(hit, list): | |
| return hit | |
| url = "https://osu.ppy.sh/api/v2/beatmaps/%d/scores/users/%d/all" % (bid, uid) | |
| def raw(): | |
| r = self._api.session.get(url, params={"mode": "osu"}, headers={"x-api-version": str(API_VERSION)}, timeout=30) | |
| if r.status_code == 429: | |
| raise RuntimeError("429 Too Many Requests(user_beatmap_scores_all)") | |
| return r | |
| r = self._call(raw, "user_beatmap_scores_all") | |
| rows: List[dict] = [] | |
| if r.status_code == 200: | |
| data = r.json() | |
| got = data.get("scores") if isinstance(data, dict) else None | |
| rows = [x for x in got if isinstance(x, dict)] if isinstance(got, list) else [] | |
| elif r.status_code != 404: | |
| raise RuntimeError("user_beatmap_scores_all HTTP %d(b/%d)" % (r.status_code, bid)) | |
| _disk_put(self.cache_dir, "uall", key, rows) | |
| return rows | |
| # ── 同水準玩家:排行榜上你前後的人 ─────────────────────────────── | |
| def _rank_page(self, page: int, country: Optional[str] = None) -> List[Any]: | |
| from ossapi import Cursor | |
| r = self._call(lambda: self._api.ranking("osu", "performance", country=country, cursor=Cursor(page=int(page))), | |
| "ranking") | |
| return list(getattr(r, "ranking", None) or []) | |
| def peers(self, u: Any, n: int = 30) -> List[int]: | |
| """全球前 10,000 名走全球榜;再深走國家榜;都拿不到回空清單(呼叫端會講)。""" | |
| rank = getattr(u, "global_rank", None) | |
| country = None | |
| if not rank or rank > RANK_PAGE * RANK_MAX_PAGE: | |
| rank = getattr(u, "country_rank", None) | |
| country = getattr(u, "country_code", None) or None | |
| if not rank or rank > RANK_PAGE * RANK_MAX_PAGE or not country: | |
| return [] | |
| page = max(1, min(RANK_MAX_PAGE, (int(rank) + RANK_PAGE - 1) // RANK_PAGE)) | |
| rows: List[Any] = [] | |
| for p in page_span(page, n): | |
| if 1 <= p <= RANK_MAX_PAGE: | |
| try: | |
| rows.extend(self._rank_page(p, country)) | |
| except Exception: | |
| continue | |
| me = int(getattr(u, "id", 0) or 0) | |
| mypp = float(getattr(u, "pp", 0.0) or 0.0) | |
| cand = [] | |
| for r in rows: | |
| uid = int(getattr(getattr(r, "user", None), "id", 0) or 0) | |
| if not uid or uid == me: | |
| continue | |
| cand.append((abs(float(getattr(r, "pp", 0.0) or 0.0) - mypp), uid)) | |
| cand.sort() | |
| seen, out = set(), [] | |
| for _d, uid in cand: | |
| if uid not in seen: | |
| seen.add(uid) | |
| out.append(uid) | |
| if len(out) >= n: | |
| break | |
| return out | |
| # ── 官方難度屬性(隨官方改版更新)與圖譜基本資料 ───────────────── | |
| def attributes(self, beatmap_id: int, mods: Any = None) -> dict: | |
| """POST /beatmaps/{id}/attributes → attributes dict(aim_difficulty、reading_difficulty、 | |
| aim_top_weighted_slider_factor…)。用 ossapi 的 session 直接打,拿**原始 JSON**, | |
| 新欄位不會被舊版模型丟掉。mods 給縮寫清單或帶 settings 的物件清單。""" | |
| body = attr_body(mods) | |
| ck = attr_key(beatmap_id, body) | |
| hit = cache_get_many(self.cache_dir, "attrs", [ck], CACHE_TTL_ATTR).get(ck) | |
| if isinstance(hit, dict): | |
| return hit | |
| self._wait() | |
| url = "https://osu.ppy.sh/api/v2/beatmaps/%d/attributes" % int(beatmap_id) | |
| r = self._api.session.post(url, json=body, timeout=30) | |
| if r.status_code == 429: | |
| p = self._slow_down() | |
| time.sleep(max(1.5, p * 5)) | |
| self._wait() | |
| r = self._api.session.post(url, json=body, timeout=30) | |
| if r.status_code != 200: | |
| raise RuntimeError("attributes HTTP %d(b/%d)" % (r.status_code, beatmap_id)) | |
| self._ok() | |
| data = r.json() or {} | |
| attrs = data.get("attributes") if isinstance(data, dict) else None | |
| if not isinstance(attrs, dict): | |
| raise RuntimeError("attributes 回應沒有 attributes(b/%d)" % beatmap_id) | |
| cache_put(self.cache_dir, "attrs", ck, attrs) | |
| return attrs | |
| def beatmap_info(self, beatmap_ids: List[int]) -> dict: | |
| """批次拿圖譜基本資料(一次最多 50):ar/od/hp/cs、物件數、狀態。回 {id: {...}}。 | |
| 每張圖各存 7 天快取;只打 API 拿沒快取的那些。""" | |
| out: dict = {} | |
| ids = [int(x) for x in dict.fromkeys(beatmap_ids)] | |
| need = [] | |
| got = cache_get_many(self.cache_dir, "info", [str(i) for i in ids], CACHE_TTL_INFO) | |
| for i in ids: | |
| hit = got.get(str(i)) | |
| if isinstance(hit, dict) and "playcount" in hit: # 2026-09-11 前的快取沒有遊玩次數 → 視同沒有 | |
| out[i] = hit | |
| else: | |
| need.append(i) | |
| for i in range(0, len(need), 50): | |
| part = need[i:i + 50] | |
| for b in self._call(lambda part=part: list(self._api.beatmaps(part)), "beatmaps"): | |
| rec = { | |
| "ar": float(getattr(b, "ar", 0.0) or 0.0), "od": float(getattr(b, "accuracy", 0.0) or 0.0), | |
| "hp": float(getattr(b, "drain", 0.0) or 0.0), "cs": float(getattr(b, "cs", 0.0) or 0.0), | |
| "hit_circle_count": int(getattr(b, "count_circles", 0) or 0), | |
| "slider_count": int(getattr(b, "count_sliders", 0) or 0), | |
| "spinner_count": int(getattr(b, "count_spinners", 0) or 0), | |
| "status": str(getattr(getattr(b, "status", None), "name", "") or "").lower(), | |
| "max_combo": int(getattr(b, "max_combo", 0) or 0), | |
| "stars": float(getattr(b, "difficulty_rating", 0.0) or 0.0), | |
| "bpm": float(getattr(b, "bpm", 0.0) or 0.0), | |
| "length": int(getattr(b, "hit_length", 0) or getattr(b, "total_length", 0) or 0), | |
| # ★遊玩次數(2026-09-11 主人:farm 要強制考量):全站打過幾次/過關幾次 | |
| "playcount": int(getattr(b, "playcount", 0) or 0), | |
| "passcount": int(getattr(b, "passcount", 0) or 0)} | |
| out[int(b.id)] = rec | |
| cache_put(self.cache_dir, "info", str(int(b.id)), rec) | |
| return out | |
| # ── ★2026-10-10 能力區域候選索引(vb_osu_index)用的圖譜搜尋 ─────────────────── | |
| def search_beatmapsets(self, q: str, cursor_string: Optional[str] = None, sort: Optional[str] = "plays_desc", | |
| status: str = "ranked", mode: int = 0) -> dict: | |
| """GET /beatmapsets/search → 原始 JSON({"beatmapsets": [...], "cursor_string": ..., "total": ...})。 | |
| 走 _call(守 PACE、429 退避重試一次);非 200 丟 RuntimeError(訊息帶 HTTP 狀態碼)。這裡不快取—— | |
| vb_osu_index 把每頁篩過的精簡結果存 30 天。2026-10-10 Space 實測:每頁 50 組、回整組所有難度(要本機再篩)、 | |
| status=ranked 會帶 ranked 與 approved、cursor_string 分頁正常。""" | |
| params: Dict[str, Any] = {"q": q, "m": int(mode), "s": status} | |
| if sort: | |
| params["sort"] = sort | |
| if cursor_string: | |
| params["cursor_string"] = cursor_string | |
| def raw(): | |
| r = self._api.session.get(SEARCH_URL, params=params, headers={"x-api-version": str(API_VERSION)}, timeout=30) | |
| if r.status_code == 429: | |
| raise RuntimeError("429 Too Many Requests(beatmapsets/search)") | |
| return r | |
| r = self._call(raw, "search") | |
| if r.status_code != 200: | |
| raise RuntimeError("beatmapsets/search HTTP %d %s" % (r.status_code, str(getattr(r, "text", ""))[:80])) | |
| try: | |
| data = r.json() | |
| except Exception: | |
| data = None | |
| if not isinstance(data, dict): | |
| raise RuntimeError("beatmapsets/search HTTP 200 但回應不是 JSON 物件") | |
| return data | |
| # ── ★2026-10-10 今天狀態(OSU_RESEARCH.md §8.1 第 6 點):只讀不存 ───────────────── | |
| def user_recent(self, user_id: int, include_fails: bool = True, limit: int = 100) -> List[dict]: | |
| """GET /users/{id}/scores/recent?include_fails=1&mode=osu&limit=… → 原始 JSON 成績清單(官方只給最近 24 小時)。 | |
| ★只讀不存:不寫磁碟、不進 Supabase;同一個行程 RECENT_TTL(2 分鐘)內同樣的問法直接回記憶體裡那份 | |
| (同一次 farm 讀兩次不必再打)。找不到人(404)回空清單;其他非 200 丟 RuntimeError。""" | |
| uid, lim = int(user_id), max(1, min(100, int(limit))) | |
| mk = (uid, bool(include_fails), lim) | |
| now = time.time() | |
| with _RECENT_LOCK: | |
| hit = _RECENT.get(mk) | |
| if hit and now - hit[0] < RECENT_TTL: | |
| return list(hit[1]) | |
| url = "https://osu.ppy.sh/api/v2/users/%d/scores/recent" % uid | |
| params = {"include_fails": 1 if include_fails else 0, "mode": "osu", "limit": lim} | |
| def raw(): | |
| r = self._api.session.get(url, params=params, headers={"x-api-version": str(API_VERSION)}, timeout=30) | |
| if r.status_code == 429: | |
| raise RuntimeError("429 Too Many Requests(scores/recent)") | |
| return r | |
| r = self._call(raw, "recent") | |
| if r.status_code == 404: | |
| rows: List[dict] = [] | |
| elif r.status_code != 200: | |
| raise RuntimeError("scores/recent HTTP %d(u/%d)" % (r.status_code, uid)) | |
| else: | |
| data = r.json() | |
| if not isinstance(data, list): | |
| raise RuntimeError("scores/recent 回應不是清單(u/%d)" % uid) | |
| rows = [x for x in data if isinstance(x, dict)] | |
| with _RECENT_LOCK: | |
| for k in [k for k, v in _RECENT.items() if now - v[0] >= RECENT_TTL]: | |
| del _RECENT[k] | |
| _RECENT[mk] = (now, rows) | |
| return list(rows) | |
| # ── 圖譜檔 ───────────────────────────────────────────────────── | |
| def osu_file(self, beatmap_id: int) -> bytes: | |
| p = os.path.join(self.cache_dir, "%d.osu" % int(beatmap_id)) | |
| if os.path.exists(p) and os.path.getsize(p) > 200: | |
| with open(p, "rb") as f: | |
| return f.read() | |
| self._wait() | |
| r = requests.get(OSU_FILE_URL % int(beatmap_id), timeout=30, | |
| headers={"User-Agent": "vanilla-bot osu farm/1.0"}) | |
| r.raise_for_status() | |
| b = r.content | |
| if len(b) < 200 or b"[HitObjects]" not in b: | |
| raise RuntimeError("圖譜檔 %d 不像 .osu(%d bytes)" % (beatmap_id, len(b))) | |
| try: | |
| os.makedirs(self.cache_dir, exist_ok=True) | |
| with open(p, "wb") as f: | |
| f.write(b) | |
| except OSError: | |
| pass # 快取寫不進去不該讓功能壞掉 | |
| return b | |
| def page_span(page: int, n: int) -> List[int]: | |
| """要湊 n 位同儕要看幾頁:自己那頁前後各 k 頁(k = ceil(n / 100)),自己那頁優先。""" | |
| k = max(1, -(-int(n) // (2 * RANK_PAGE))) | |
| out = [page] | |
| for d in range(1, k + 1): | |
| out += [page - d, page + d] | |
| return out | |
| class _UserView: | |
| def __init__(self, **kw): | |
| self.__dict__.update(kw) | |
| def __repr__(self): | |
| return "User(%s)" % self.__dict__ | |
| # ── ★2026-10-10 能力區域候選索引的狀態行(/health)───────────────────────────────── | |
| # 一次性實測(9ef01f5:/health 第一次讀時背景打 2 個搜尋請求)已完成、結果記在 OSU_RESEARCH.md §8.1 第 7 點 → | |
| # 換成索引本身的狀態:vb_osu_index.build_index 每建一次呼叫 index_note(),index_line() 給 /health 看。不打 API。 | |
| _INDEX: Dict[str, Any] = {} | |
| _INDEX_LOCK = threading.Lock() | |
| def index_note(stats: Dict[str, Any]) -> None: | |
| """vb_osu_index.build_index 建完一次就記下來(只留最近一次+開機以來的累計)。""" | |
| with _INDEX_LOCK: | |
| builds = int(_INDEX.get("builds", 0)) + 1 | |
| reqs = int(_INDEX.get("requests_all", 0)) + int(stats.get("requests", 0) or 0) | |
| _INDEX.clear() | |
| _INDEX.update({k: stats.get(k) for k in ("segments", "pages", "cached", "requests", "candidates", "sec", | |
| "truncated", "truncated_reason", "page_capped")}) | |
| _INDEX.update(at=time.time(), builds=builds, requests_all=reqs) | |
| def index_pages_on_disk(cache_dir: Optional[str] = None, ttl: float = CACHE_TTL_SRCH) -> int: | |
| """磁碟上還沒過期的搜尋頁數(kind "srch")。Supabase 那層不數(要多一次查詢)。""" | |
| d = os.path.join(cache_dir or CACHE_DIR, "cache", "srch") | |
| now, n = time.time(), 0 | |
| try: | |
| for fn in os.listdir(d): | |
| if fn.endswith(".json"): | |
| try: | |
| if now - os.path.getmtime(os.path.join(d, fn)) <= ttl: | |
| n += 1 | |
| except OSError: | |
| pass | |
| except OSError: | |
| return 0 | |
| return n | |
| def index_line(cache_dir: Optional[str] = None) -> str: | |
| """「osu 候選索引:磁碟快取 N 頁(30 天內);最近一次建…」——/health 用。""" | |
| head = "osu 候選索引:磁碟快取 %d 頁(%d 天內)" % (index_pages_on_disk(cache_dir), CACHE_TTL_SRCH // 86400) | |
| with _INDEX_LOCK: | |
| p = dict(_INDEX) | |
| if not p: | |
| return head + ";這次開機還沒建過" | |
| ago = max(0, int(time.time() - float(p.get("at") or 0))) | |
| ago_s = ("%d 秒前" % ago) if ago < 120 else ("%d 分鐘前" % (ago // 60)) if ago < 7200 else ("%d 小時前" % (ago // 3600)) | |
| line = ("%s;最近一次建(%s):%s 段、%s 頁(快取命中 %s)、打了 %s 個請求、%.1f 秒、篩後 %s 張;開機以來建 %d 次、共 %d 個請求" % ( | |
| head, ago_s, p.get("segments"), p.get("pages"), p.get("cached"), p.get("requests"), float(p.get("sec") or 0), | |
| p.get("candidates"), int(p.get("builds") or 0), int(p.get("requests_all") or 0))) | |
| if p.get("truncated"): | |
| line += ";★截斷(%s)" % (p.get("truncated_reason") or "請求數上限") | |
| elif p.get("page_capped"): | |
| line += ";頁數到上限(只取各段依遊玩次數排序前面的)" | |
| return line | |
| def probe_search_start() -> None: | |
| """舊的一次性實測入口(vb_health 還在叫):實測已完成,現在什麼都不做、不打 API。改接 index_line() 後可刪。""" | |
| return None | |
| def probe_line() -> str: | |
| """舊名字的相容包裝 → index_line()。""" | |
| return index_line() | |
| def _played_meta(it: Any) -> Dict[str, str]: | |
| """most_played 一列(原始 JSON 或 ossapi 物件)的圖名:beatmap.version、beatmapset.title/artist/creator。""" | |
| def g(o: Any, k: str) -> Any: | |
| return o.get(k) if isinstance(o, dict) else getattr(o, k, None) | |
| bm, bs = g(it, "beatmap"), g(it, "beatmapset") | |
| out = {"version": g(bm, "version") if bm is not None else None, | |
| "title": g(bs, "title") if bs is not None else None, | |
| "artist": g(bs, "artist") if bs is not None else None, | |
| "creator": g(bs, "creator") if bs is not None else None} | |
| return {k: str(v) for k, v in out.items() if v} | |
| def from_env() -> Optional[Client]: | |
| cid = os.getenv("OSU_CLIENT_ID", "").strip() | |
| sec = os.getenv("OSU_CLIENT_SECRET", "").strip() | |
| if not cid or not sec: | |
| return None | |
| if not sb_on(): # 跟 bot 同一組 Supabase(HF Secrets);沒設就只有磁碟 | |
| configure_cache(os.getenv("SUPABASE_URL", ""), os.getenv("SUPABASE_SERVICE_KEY") or os.getenv("SUPABASE_KEY", "")) | |
| return Client(cid, sec) | |