Spaces:
Running
Running
更新 7 個檔(discordbot.py、vb_osu_farm.py、vb_osu_api.py、vb_osu_backtest.py…)
Browse files- data/echo/recent.npz +2 -2
- discordbot.py +45 -0
- vb_help.py +1 -0
- vb_osu_api.py +52 -0
- vb_osu_backtest.py +371 -0
- vb_osu_farm.py +68 -50
data/echo/recent.npz
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6c20952c77c79168e4ebca6fb08667cc62497590f13206d3adfae75bf88731f3
|
| 3 |
+
size 306007
|
discordbot.py
CHANGED
|
@@ -10473,6 +10473,17 @@ async def _osu_finish(interaction: discord.Interaction, msg, text: str, brief: O
|
|
| 10473 |
await interaction.followup.send(shown, **kw)
|
| 10474 |
|
| 10475 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10476 |
async def _osu_cached(interaction: discord.Interaction, hit: Tuple[float, str, Optional[str]]) -> None:
|
| 10477 |
note = f"\n-# 快取:{(time.time() - hit[0]) / 60:.0f} 分鐘前算的,6 小時更新一次"
|
| 10478 |
v = _split_view(hit[2], hit[1])
|
|
@@ -10585,6 +10596,40 @@ async def osu_edge(interaction: discord.Interaction, 玩家: str):
|
|
| 10585 |
await _osu_finish(interaction, msg, text, brief)
|
| 10586 |
|
| 10587 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10588 |
# ── /delta:三角洲行動改槍碼+配件 ──
|
| 10589 |
# ★2026-09-23 主人「雞肋指令全做」:/delta news 拿掉(聊天問「三角洲最新更新」走同一支 get_game_news)、
|
| 10590 |
# /delta player 拿掉(沒有官方 API,只是拿玩家名去網路搜尋,Jina 額度用完時幾乎都回「找不到」);
|
|
|
|
| 10473 |
await interaction.followup.send(shown, **kw)
|
| 10474 |
|
| 10475 |
|
| 10476 |
+
async def _osu_finish_long(interaction: discord.Interaction, msg, text: str) -> None:
|
| 10477 |
+
"""把「⏳ …」那則換成結果;超過一則的長度就切塊,後面的接著送(回測報告沒有手機精簡版)。"""
|
| 10478 |
+
parts = split_for_discord_fenced(text, 1900) or [text[:1900]]
|
| 10479 |
+
try:
|
| 10480 |
+
await msg.edit(content=parts[0])
|
| 10481 |
+
except Exception:
|
| 10482 |
+
await interaction.followup.send(parts[0])
|
| 10483 |
+
for p in parts[1:]:
|
| 10484 |
+
await interaction.followup.send(p)
|
| 10485 |
+
|
| 10486 |
+
|
| 10487 |
async def _osu_cached(interaction: discord.Interaction, hit: Tuple[float, str, Optional[str]]) -> None:
|
| 10488 |
note = f"\n-# 快取:{(time.time() - hit[0]) / 60:.0f} 分鐘前算的,6 小時更新一次"
|
| 10489 |
v = _split_view(hit[2], hit[1])
|
|
|
|
| 10596 |
await _osu_finish(interaction, msg, text, brief)
|
| 10597 |
|
| 10598 |
|
| 10599 |
+
@osu_group.command(name="backtest", description="(主人)用現有資料回測 farm 的預測:藏起你每張成績再預測、同儕互驗,看偏差與誤差分布")
|
| 10600 |
+
@app_commands.describe(玩家="osu! 使用者名稱或數字 ID")
|
| 10601 |
+
@app_commands.autocomplete(玩家=_recent_ac("osu", "玩家"))
|
| 10602 |
+
async def osu_backtest(interaction: discord.Interaction, 玩家: str):
|
| 10603 |
+
# ★2026-10-08 主人:「驗證樣本太花時間,一定有現有資料,你為什麼不用」→ 不等人去打:top 榜、打過沒進榜的、同儕互驗(vb_osu_backtest)
|
| 10604 |
+
if not await _is_owner_quiet(interaction.user):
|
| 10605 |
+
await interaction.response.send_message("回測只有主人能跑喵~(一次要打上千次 osu! API)", ephemeral=True)
|
| 10606 |
+
return
|
| 10607 |
+
await interaction.response.defer()
|
| 10608 |
+
who = 玩家.strip()
|
| 10609 |
+
_recent_note(interaction, "osu", "玩家", who)
|
| 10610 |
+
try:
|
| 10611 |
+
import vb_osu_api as _OA
|
| 10612 |
+
import vb_osu_backtest as _OB
|
| 10613 |
+
except Exception as e:
|
| 10614 |
+
await interaction.followup.send(_fail("osu 模組載入", e, 100))
|
| 10615 |
+
return
|
| 10616 |
+
client = _OA.from_env()
|
| 10617 |
+
if client is None:
|
| 10618 |
+
await interaction.followup.send("還沒設定 osu! API 金鑰喵~請在 HF Secrets 加 `OSU_CLIENT_ID` 與 `OSU_CLIENT_SECRET`。")
|
| 10619 |
+
return
|
| 10620 |
+
msg = await interaction.followup.send("⏳ /osu backtest:讀取你的成績…", wait=True)
|
| 10621 |
+
progress = _osu_progress(msg, "/osu backtest")
|
| 10622 |
+
try:
|
| 10623 |
+
text = await asyncio.wait_for(
|
| 10624 |
+
asyncio.to_thread(_OB.run, client, who, lambda s: print(s, flush=True), progress),
|
| 10625 |
+
timeout=800) # Discord 的互動 15 分鐘失效,留一點餘裕
|
| 10626 |
+
except asyncio.TimeoutError:
|
| 10627 |
+
text = "算太久了喵~超過 13 分鐘(Discord 的互動 15 分鐘就失效),多半是 osu! API 限流;等幾分鐘再試"
|
| 10628 |
+
except Exception as e:
|
| 10629 |
+
text = _fail("/osu backtest", e)
|
| 10630 |
+
await _osu_finish_long(interaction, msg, text)
|
| 10631 |
+
|
| 10632 |
+
|
| 10633 |
# ── /delta:三角洲行動改槍碼+配件 ──
|
| 10634 |
# ★2026-09-23 主人「雞肋指令全做」:/delta news 拿掉(聊天問「三角洲最新更新」走同一支 get_game_news)、
|
| 10635 |
# /delta player 拿掉(沒有官方 API,只是拿玩家名去網路搜尋,Jina 額度用完時幾乎都回「找不到」);
|
vb_help.py
CHANGED
|
@@ -66,6 +66,7 @@ PAGES: Dict[str, str] = {
|
|
| 66 |
"games": """## 🎮 遊戲
|
| 67 |
`/osu farm 玩家` — 找最能加總 pp 的圖(`難度` 選挑戰會放寬範圍)
|
| 68 |
`/osu edge 玩家` — 跟同水準玩家比,你哪類圖強、哪類弱
|
|
|
|
| 69 |
`/valorant 玩家` — 段位與最近對戰(格式 `名稱#Tag`)
|
| 70 |
`/delta 武器` — 三角洲改槍碼+配件
|
| 71 |
-# 遊戲版本更新直接問香草,例如「三角洲最新更新」""",
|
|
|
|
| 66 |
"games": """## 🎮 遊戲
|
| 67 |
`/osu farm 玩家` — 找最能加總 pp 的圖(`難度` 選挑戰會放寬範圍)
|
| 68 |
`/osu edge 玩家` — 跟同水準玩家比,你哪類圖強、哪類弱
|
| 69 |
+
`/osu backtest 玩家` — (主人)用現有成績回測 farm 的預測準不準
|
| 70 |
`/valorant 玩家` — 段位與最近對戰(格式 `名稱#Tag`)
|
| 71 |
`/delta 武器` — 三角洲改槍碼+配件
|
| 72 |
-# 遊戲版本更新直接問香草,例如「三角洲最新更新」""",
|
vb_osu_api.py
CHANGED
|
@@ -37,6 +37,7 @@ RANK_MAX_PAGE = 200 # API 只給到第 200 頁(前 10,000 名)
|
|
| 37 |
CACHE_TTL_ATTR = 7 * 86400
|
| 38 |
CACHE_TTL_INFO = 7 * 86400
|
| 39 |
CACHE_TTL_PLAYED = 3600 # 你自己「打過幾次」的清單(most_played):1 小時(剛打的要看得到)
|
|
|
|
| 40 |
MOST_PLAYED_PAGES = 5 # most_played 每頁 100 張、依次數遞減;只抓前幾頁(後面都是打過一兩次的)
|
| 41 |
|
| 42 |
|
|
@@ -388,6 +389,57 @@ class Client:
|
|
| 388 |
cache_put(self.cache_dir, "played", key, {str(k): v for k, v in out.items()})
|
| 389 |
return out
|
| 390 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
# ── 同水準玩家:排行榜上你前後的人 ───────────────────────────────
|
| 392 |
def _rank_page(self, page: int, country: Optional[str] = None) -> List[Any]:
|
| 393 |
from ossapi import Cursor
|
|
|
|
| 37 |
CACHE_TTL_ATTR = 7 * 86400
|
| 38 |
CACHE_TTL_INFO = 7 * 86400
|
| 39 |
CACHE_TTL_PLAYED = 3600 # 你自己「打過幾次」的清單(most_played):1 小時(剛打的要看得到)
|
| 40 |
+
CACHE_TTL_UBEST = 6 * 3600 # ★2026-10-08 /osu backtest:你在某張圖的最佳/全部成績;只存磁碟(一次幾百張,不進 Supabase 佔表)
|
| 41 |
MOST_PLAYED_PAGES = 5 # most_played 每頁 100 張、依次數遞減;只抓前幾頁(後面都是打過一兩次的)
|
| 42 |
|
| 43 |
|
|
|
|
| 389 |
cache_put(self.cache_dir, "played", key, {str(k): v for k, v in out.items()})
|
| 390 |
return out
|
| 391 |
|
| 392 |
+
# ── 單圖成績(★2026-10-08 /osu backtest 用)──────────────────────
|
| 393 |
+
def user_beatmap_score(self, beatmap_id: int, user_id: int) -> Optional[dict]:
|
| 394 |
+
"""某人在某張圖的最好成績(GET /beatmaps/{id}/scores/users/{uid};沒過關過=404 → None)。回原始 JSON 的 score。
|
| 395 |
+
沒有也記起來({"score": None}),回測不會對同一張一直問。"""
|
| 396 |
+
bid, uid = int(beatmap_id), int(user_id)
|
| 397 |
+
key = "%d_%d" % (uid, bid)
|
| 398 |
+
hit = cache_get(self.cache_dir, "ubest", key, CACHE_TTL_UBEST)
|
| 399 |
+
if isinstance(hit, dict) and "score" in hit:
|
| 400 |
+
return hit["score"]
|
| 401 |
+
url = "https://osu.ppy.sh/api/v2/beatmaps/%d/scores/users/%d" % (bid, uid)
|
| 402 |
+
|
| 403 |
+
def raw():
|
| 404 |
+
r = self._api.session.get(url, params={"mode": "osu"}, headers={"x-api-version": str(API_VERSION)}, timeout=30)
|
| 405 |
+
if r.status_code == 429:
|
| 406 |
+
raise RuntimeError("429 Too Many Requests(user_beatmap_score)")
|
| 407 |
+
return r
|
| 408 |
+
r = self._call(raw, "user_beatmap_score")
|
| 409 |
+
score = None
|
| 410 |
+
if r.status_code == 200:
|
| 411 |
+
data = r.json()
|
| 412 |
+
score = data.get("score") if isinstance(data, dict) else None
|
| 413 |
+
elif r.status_code != 404:
|
| 414 |
+
raise RuntimeError("user_beatmap_score HTTP %d(b/%d)" % (r.status_code, bid))
|
| 415 |
+
_disk_put(self.cache_dir, "ubest", key, {"score": score})
|
| 416 |
+
return score
|
| 417 |
+
|
| 418 |
+
def user_beatmap_scores_all(self, beatmap_id: int, user_id: int) -> List[dict]:
|
| 419 |
+
"""某人在某張圖的全部成績(GET …/scores/users/{uid}/all;lazer 時代的成績才有多筆,stable 只有最好的一筆或空)。"""
|
| 420 |
+
bid, uid = int(beatmap_id), int(user_id)
|
| 421 |
+
key = "%d_%d" % (uid, bid)
|
| 422 |
+
hit = cache_get(self.cache_dir, "uall", key, CACHE_TTL_UBEST)
|
| 423 |
+
if isinstance(hit, list):
|
| 424 |
+
return hit
|
| 425 |
+
url = "https://osu.ppy.sh/api/v2/beatmaps/%d/scores/users/%d/all" % (bid, uid)
|
| 426 |
+
|
| 427 |
+
def raw():
|
| 428 |
+
r = self._api.session.get(url, params={"mode": "osu"}, headers={"x-api-version": str(API_VERSION)}, timeout=30)
|
| 429 |
+
if r.status_code == 429:
|
| 430 |
+
raise RuntimeError("429 Too Many Requests(user_beatmap_scores_all)")
|
| 431 |
+
return r
|
| 432 |
+
r = self._call(raw, "user_beatmap_scores_all")
|
| 433 |
+
rows: List[dict] = []
|
| 434 |
+
if r.status_code == 200:
|
| 435 |
+
data = r.json()
|
| 436 |
+
got = data.get("scores") if isinstance(data, dict) else None
|
| 437 |
+
rows = [x for x in got if isinstance(x, dict)] if isinstance(got, list) else []
|
| 438 |
+
elif r.status_code != 404:
|
| 439 |
+
raise RuntimeError("user_beatmap_scores_all HTTP %d(b/%d)" % (r.status_code, bid))
|
| 440 |
+
_disk_put(self.cache_dir, "uall", key, rows)
|
| 441 |
+
return rows
|
| 442 |
+
|
| 443 |
# ── 同水準玩家:排行榜上你前後的人 ───────────────────────────────
|
| 444 |
def _rank_page(self, page: int, country: Optional[str] = None) -> List[Any]:
|
| 445 |
from ossapi import Cursor
|
vb_osu_backtest.py
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# -*- coding: utf-8 -*-
|
| 2 |
+
"""/osu backtest:用現有資料回測 /osu farm 的預測(主人 2026-10-08:「驗證樣本太花時間,一定有現有資料,你為什麼不用」)。
|
| 3 |
+
|
| 4 |
+
主人定的目標:預測跟實際(3 次以內打出來的)的差,不能超過「當天手感 + 極小的統計誤差」。
|
| 5 |
+
這支先把「統計誤差」量出來、看預測有沒有系統性偏高;手感帶寬只有 lazer 玩家量得到(同一張圖的全部成績)。
|
| 6 |
+
|
| 7 |
+
樣本(全部是 API 現成的,不用等人去打):
|
| 8 |
+
A 你的 top 100:每張有實際 pp。把這張藏起來(你的 acc 趨勢、FC 率都不含它)再預測。
|
| 9 |
+
B most_played 前 500 張裡不在 top 100 的:查你在那張的最好成績(有過關才有)。這些是「打了但沒進榜」的樣本,
|
| 10 |
+
補只看 top 榜的倖存者偏差(top 榜是你最好的那些,單看它預測一定偏低)。
|
| 11 |
+
C A+B 裡打過 ≤ ATTEMPTS 次的:主人定義的「3 次以內」。
|
| 12 |
+
D 同儕互驗:你樣本裡的 (圖, mods) 其他同儕也打過的,把那個人藏起來、用剩下的人+他自己的榜預測他。零額外 API。
|
| 13 |
+
|
| 14 |
+
預測兩種定義(都走 farm 現在的流程:同儕在這張圖的 acc/miss 中位數 × 你的係數,跟你自己的趨勢混合;pp 用校準過的引擎):
|
| 15 |
+
單次期望=P(FC)×FC 的 pp + (1−P(FC))×掉 miss 的 pp(farm 現在用的)
|
| 16 |
+
3 次內最佳=P(FC) 換成 1−(1−P(FC))^3
|
| 17 |
+
|
| 18 |
+
誤差=(預測 − 實際) ÷ 實際。報告:偏差(中位數,正=預測偏高)、|誤差| 中位、p90、±10% 內的比例;按樣本人數、mods、星數分組。
|
| 19 |
+
純函式為主;API 由 client 注入(跟 vb_osu_farm 同一個鴨子型別,多 user_beatmap_score/user_beatmap_scores_all)。
|
| 20 |
+
"""
|
| 21 |
+
import statistics
|
| 22 |
+
import time
|
| 23 |
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
| 24 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple
|
| 25 |
+
|
| 26 |
+
import vb_osu_farm as F
|
| 27 |
+
|
| 28 |
+
ATTEMPTS = 3
|
| 29 |
+
EXTRA_MAX = 400 # B 最多查幾張(most_played 500 張扣掉 top 100;打過 ≤3 次的優先)
|
| 30 |
+
PEER_LOO_MAX = 600 # D 最多幾個樣本
|
| 31 |
+
FEEL_MAX = 60 # lazer 手感:最多看幾張圖的全部成績
|
| 32 |
+
MIN_N = 8 # 一組少於這麼多樣本不印
|
| 33 |
+
THREADS = 8
|
| 34 |
+
STAR_BANDS = ((0.0, 4.0, "<4★"), (4.0, 5.0, "4–5★"), (5.0, 6.0, "5–6★"), (6.0, 99.0, "≥6★"))
|
| 35 |
+
MODS_SHOW = ("", "HD", "HR", "DT", "DTHD", "HDHR")
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def rel_err(pred: float, actual: float) -> float:
|
| 39 |
+
return (float(pred) - float(actual)) / float(actual)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def p_best_of(p: float, k: int = ATTEMPTS) -> float:
|
| 43 |
+
"""單次 FC 機率 p → k 次內至少一次 FC 的機率。"""
|
| 44 |
+
p = max(0.0, min(1.0, float(p)))
|
| 45 |
+
return 1.0 - (1.0 - p) ** int(k)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def summarize(errs: List[float]) -> Dict[str, Any]:
|
| 49 |
+
xs = [float(e) for e in errs]
|
| 50 |
+
if not xs:
|
| 51 |
+
return {"n": 0}
|
| 52 |
+
ab = sorted(abs(x) for x in xs)
|
| 53 |
+
return {"n": len(xs), "bias": statistics.median(xs), "mae": statistics.median(ab),
|
| 54 |
+
"p90": ab[min(len(ab) - 1, int(round(0.9 * (len(ab) - 1))))],
|
| 55 |
+
"in10": sum(1 for a in ab if a <= 0.10) / len(ab), "in5": sum(1 for a in ab if a <= 0.05) / len(ab)}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def fmt(s: Dict[str, Any]) -> str:
|
| 59 |
+
if not s or not s.get("n"):
|
| 60 |
+
return "沒有樣本"
|
| 61 |
+
return "n=%d 偏差 %+.1f%%、|誤差| 中位 %.1f%%、p90 %.0f%%、±10%% 內 %.0f%%" % (
|
| 62 |
+
s["n"], s["bias"] * 100, s["mae"] * 100, s["p90"] * 100, s["in10"] * 100)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# ── 一張圖的預測(藏起這張之後) ─────────────────────────────────────
|
| 66 |
+
def predict_one(c: Optional[Dict[str, Any]], own_scores: List[Dict[str, Any]], peer_scores: List[Dict[str, Any]],
|
| 67 |
+
calc: Any, bid: int, mods: Any, mods_key: str, lazer: bool,
|
| 68 |
+
factor: Optional[float] = None) -> Optional[Dict[str, Any]]:
|
| 69 |
+
"""c=同儕在 (圖, mods) 的聚合(vb_osu_farm.aggregate 的一格;None=沒同儕打過,只能用自己的趨勢)。
|
| 70 |
+
own_scores 裡這張圖的成績先拿掉,再算 acc 趨勢、FC 率分段、acc 係數——跟 farm 推薦沒打過的圖時拿到的資訊一樣。
|
| 71 |
+
回 {stars, acc, p_fc, miss, n, exp1(單次), exp3(3 次內最佳), fc_pp};自己的趨勢也沒有(成績太少)→ None。"""
|
| 72 |
+
wo = [s for s in own_scores if int(s.get("beatmap_id") or 0) != int(bid)]
|
| 73 |
+
model = F.acc_model(wo)
|
| 74 |
+
prof = F.user_profile(wo)
|
| 75 |
+
if factor is None:
|
| 76 |
+
factor = F.acc_factor(wo, peer_scores) if peer_scores else 1.0
|
| 77 |
+
probe = calc(bid, mods, 100.0, 0, None, lazer)
|
| 78 |
+
stars = float(probe["stars"])
|
| 79 |
+
p_fc, miss = F.fc_at(prof, stars)
|
| 80 |
+
miss = int(miss) if p_fc < 1.0 else 0
|
| 81 |
+
if c is not None and c.get("accs"):
|
| 82 |
+
p = F.predict(c, factor, model, stars)
|
| 83 |
+
acc, n = float(p["acc"]), int(p["n"])
|
| 84 |
+
else:
|
| 85 |
+
own = F.acc_at(model, stars)
|
| 86 |
+
if own is None:
|
| 87 |
+
return None
|
| 88 |
+
acc, n = float(own), 0
|
| 89 |
+
fc = calc(bid, mods, acc, 0, None, lazer)
|
| 90 |
+
combo = max(1, int(round(float(fc["max_combo"] or 1) * float(prof["combo_ratio"]))))
|
| 91 |
+
bad = calc(bid, mods, acc, miss, combo, lazer) if miss else fc
|
| 92 |
+
p3 = p_best_of(p_fc)
|
| 93 |
+
return {"stars": stars, "acc": acc, "p_fc": float(p_fc), "miss": miss, "n": n, "fc_pp": float(fc["pp"]),
|
| 94 |
+
"exp1": p_fc * fc["pp"] + (1.0 - p_fc) * bad["pp"],
|
| 95 |
+
"exp3": p3 * fc["pp"] + (1.0 - p3) * bad["pp"]}
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
# ── 樣本 A+B:你的成績 ───────────────────────────────────────────────
|
| 99 |
+
def user_samples(client: Any, uid: int, user_scores: List[Dict[str, Any]],
|
| 100 |
+
log: Callable[[str], None] = lambda s: None, progress: Optional[Callable[[str], None]] = None,
|
| 101 |
+
extra_max: int = EXTRA_MAX) -> Tuple[List[Dict[str, Any]], Dict[int, int]]:
|
| 102 |
+
"""回 ([{src: top|extra, score, plays}], most_played)。extra=most_played 裡不在 top 的,查單圖最佳成績(並行、client 節流)。"""
|
| 103 |
+
plays: Dict[int, int] = {}
|
| 104 |
+
if hasattr(client, "most_played"):
|
| 105 |
+
try:
|
| 106 |
+
plays = {int(k): int(v) for k, v in client.most_played(int(uid)).items()}
|
| 107 |
+
except Exception as e:
|
| 108 |
+
log("[osu 回測] most_played 失敗:%s: %s" % (type(e).__name__, str(e)[:80]))
|
| 109 |
+
best: Dict[int, Dict[str, Any]] = {}
|
| 110 |
+
for s in user_scores:
|
| 111 |
+
if not s.get("pp") or not s.get("beatmap_id"):
|
| 112 |
+
continue
|
| 113 |
+
b = int(s["beatmap_id"])
|
| 114 |
+
if b not in best or s["pp"] > best[b]["pp"]:
|
| 115 |
+
best[b] = s
|
| 116 |
+
out = [{"src": "top", "score": s, "plays": plays.get(b)} for b, s in best.items()]
|
| 117 |
+
extra = sorted([b for b in plays if b not in best], key=lambda b: (plays[b] > ATTEMPTS, -plays[b], b))[:int(extra_max)]
|
| 118 |
+
if not extra or not hasattr(client, "user_beatmap_score"):
|
| 119 |
+
return out, plays
|
| 120 |
+
n_got, n_fail = 0, 0
|
| 121 |
+
with ThreadPoolExecutor(max_workers=THREADS) as ex:
|
| 122 |
+
futs = {ex.submit(client.user_beatmap_score, b, int(uid)): b for b in extra}
|
| 123 |
+
for i, fu in enumerate(as_completed(futs), 1):
|
| 124 |
+
b = futs[fu]
|
| 125 |
+
try:
|
| 126 |
+
raw = fu.result()
|
| 127 |
+
except Exception as e:
|
| 128 |
+
n_fail += 1
|
| 129 |
+
if n_fail <= 3:
|
| 130 |
+
log("[osu 回測] 單圖成績 b/%d 失敗:%s: %s" % (b, type(e).__name__, str(e)[:60]))
|
| 131 |
+
continue
|
| 132 |
+
if raw:
|
| 133 |
+
s = F.norm_score(raw)
|
| 134 |
+
if s.get("pp") and s.get("beatmap_id"):
|
| 135 |
+
out.append({"src": "extra", "score": s, "plays": plays.get(int(s["beatmap_id"]))})
|
| 136 |
+
n_got += 1
|
| 137 |
+
if progress and i % 25 == 0:
|
| 138 |
+
progress("查你打過但沒進榜的圖 %d/%d" % (i, len(extra)))
|
| 139 |
+
log("[osu 回測] 樣本:top %d、沒進榜 %d(查 %d 張、失敗 %d)" % (len(best), n_got, len(extra), n_fail))
|
| 140 |
+
return out, plays
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# ── 樣本 D:同儕互驗 ───────────────────────────────────────────────────
|
| 144 |
+
def peer_samples(cands: Dict[Tuple[int, str], Dict[str, Any]], peer_scores: List[Dict[str, Any]],
|
| 145 |
+
keys: List[Tuple[int, str]], calc: Any, max_n: int = PEER_LOO_MAX,
|
| 146 |
+
progress: Optional[Callable[[str], None]] = None) -> List[Dict[str, Any]]:
|
| 147 |
+
"""keys 裡的 (圖, mods) 有 ≥2 位同儕打過的:每位輪流藏起來,用其他人+他自己的 top 榜預測他。"""
|
| 148 |
+
by_user: Dict[int, List[Dict[str, Any]]] = {}
|
| 149 |
+
for s in peer_scores:
|
| 150 |
+
by_user.setdefault(int(s["user_id"]), []).append(s)
|
| 151 |
+
out: List[Dict[str, Any]] = []
|
| 152 |
+
seen = set()
|
| 153 |
+
for key in keys:
|
| 154 |
+
if key in seen:
|
| 155 |
+
continue
|
| 156 |
+
seen.add(key)
|
| 157 |
+
c = cands.get(key)
|
| 158 |
+
if not c or len(c.get("plays") or []) < 2:
|
| 159 |
+
continue
|
| 160 |
+
bid, mkey = key
|
| 161 |
+
for i, (uid, pp, _st) in enumerate(c["plays"]):
|
| 162 |
+
keep = [j for j in range(len(c["plays"])) if j != i]
|
| 163 |
+
c_wo = dict(c, plays=[c["plays"][j] for j in keep], pps=[c["pps"][j] for j in keep],
|
| 164 |
+
accs=[c["accs"][j] for j in keep], misses=[c["misses"][j] for j in keep],
|
| 165 |
+
combos=[c["combos"][j] for j in keep], users={c["plays"][j][0] for j in keep})
|
| 166 |
+
own = by_user.get(int(uid), [])
|
| 167 |
+
s_own = next((s for s in own if int(s["beatmap_id"]) == int(bid) and F.mods_key(s["mods"]) == mkey), None)
|
| 168 |
+
if not s_own or not pp:
|
| 169 |
+
continue
|
| 170 |
+
others = [s for s in peer_scores if int(s["user_id"]) != int(uid)]
|
| 171 |
+
try:
|
| 172 |
+
r = predict_one(c_wo, own, others, calc, int(bid), s_own["mods"], mkey, bool(s_own["lazer"]))
|
| 173 |
+
except Exception:
|
| 174 |
+
continue
|
| 175 |
+
if not r:
|
| 176 |
+
continue
|
| 177 |
+
out.append({"uid": int(uid), "bid": int(bid), "mkey": mkey, "actual": float(pp), "stars": r["stars"],
|
| 178 |
+
"n": r["n"], "e1": rel_err(r["exp1"], pp), "e3": rel_err(r["exp3"], pp)})
|
| 179 |
+
if len(out) >= int(max_n):
|
| 180 |
+
return out
|
| 181 |
+
if progress and len(out) % 100 < len(c["plays"]):
|
| 182 |
+
progress("同儕互驗 %d 個樣本" % len(out))
|
| 183 |
+
return out
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
# ── 手感帶寬(lazer:同一張圖的全部成績) ─────────────────────────────
|
| 187 |
+
def feel_samples(client: Any, uid: int, samples: List[Dict[str, Any]], plays: Dict[int, int], user_lazer: bool,
|
| 188 |
+
log: Callable[[str], None] = lambda s: None, progress: Optional[Callable[[str], None]] = None,
|
| 189 |
+
max_n: int = FEEL_MAX) -> List[Dict[str, Any]]:
|
| 190 |
+
"""打過 ≥ ATTEMPTS 次的圖,拿你在那張的全部成績算 pp 分散:全距比例、最好 vs 中位。stable 玩家沒有多筆 → 空。"""
|
| 191 |
+
if not user_lazer or not hasattr(client, "user_beatmap_scores_all"):
|
| 192 |
+
return []
|
| 193 |
+
ids = []
|
| 194 |
+
for smp in samples:
|
| 195 |
+
b = int(smp["score"]["beatmap_id"])
|
| 196 |
+
if (plays.get(b) or 0) >= ATTEMPTS and b not in ids:
|
| 197 |
+
ids.append(b)
|
| 198 |
+
ids = ids[:int(max_n)]
|
| 199 |
+
out: List[Dict[str, Any]] = []
|
| 200 |
+
if not ids:
|
| 201 |
+
return out
|
| 202 |
+
with ThreadPoolExecutor(max_workers=THREADS) as ex:
|
| 203 |
+
futs = {ex.submit(client.user_beatmap_scores_all, b, int(uid)): b for b in ids}
|
| 204 |
+
for i, fu in enumerate(as_completed(futs), 1):
|
| 205 |
+
try:
|
| 206 |
+
rows = fu.result() or []
|
| 207 |
+
except Exception as e:
|
| 208 |
+
log("[osu 回測] 全部成績 b/%d 失敗:%s" % (futs[fu], type(e).__name__))
|
| 209 |
+
continue
|
| 210 |
+
pps = sorted(float(x.get("pp")) for x in rows if isinstance(x, dict) and x.get("pp"))
|
| 211 |
+
if len(pps) >= 2:
|
| 212 |
+
med = statistics.median(pps)
|
| 213 |
+
out.append({"bid": futs[fu], "n": len(pps), "spread": (pps[-1] - pps[0]) / pps[-1],
|
| 214 |
+
"best_vs_median": (pps[-1] - med) / med if med else 0.0})
|
| 215 |
+
if progress and i % 20 == 0:
|
| 216 |
+
progress("手感:查同一張圖的全部成績 %d/%d" % (i, len(ids)))
|
| 217 |
+
return out
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
# ── 報告 ───────────────────────────────────────────────────────────────
|
| 221 |
+
def _band(stars: float) -> str:
|
| 222 |
+
for lo, hi, name in STAR_BANDS:
|
| 223 |
+
if lo <= stars < hi:
|
| 224 |
+
return name
|
| 225 |
+
return STAR_BANDS[-1][2]
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def _n_bucket(n: int) -> str:
|
| 229 |
+
return ("0 人", "1 人", "2 人")[n] if n < 3 else "≥3 人"
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def _line(label: str, rows: List[Dict[str, Any]], both: bool = False) -> Optional[str]:
|
| 233 |
+
if len(rows) < MIN_N:
|
| 234 |
+
return None
|
| 235 |
+
s1, s3 = summarize([r["e1"] for r in rows]), summarize([r["e3"] for r in rows])
|
| 236 |
+
if both:
|
| 237 |
+
return " %s:單次 %s\n 3 次內 %s" % (label, fmt(s1), fmt(s3))
|
| 238 |
+
return " %s:%s;3 次內偏差 %+.1f%%" % (label, fmt(s1), s3["bias"] * 100)
|
| 239 |
+
|
| 240 |
+
|
| 241 |
+
def format_report(username: str, user_pp: float, rows: List[Dict[str, Any]], peer_rows: List[Dict[str, Any]],
|
| 242 |
+
feel: List[Dict[str, Any]], engine: str, peers_n: int, n_err: int = 0, n_skip: int = 0,
|
| 243 |
+
err_top: str = "", elapsed: Optional[float] = None, user_lazer: bool = True) -> str:
|
| 244 |
+
top = [r for r in rows if r["src"] == "top"]
|
| 245 |
+
extra = [r for r in rows if r["src"] == "extra"]
|
| 246 |
+
few = [r for r in rows if r.get("plays") is not None and r["plays"] <= ATTEMPTS]
|
| 247 |
+
head = ["🧪 **farm 回測** · %s(%.0f pp)· 引擎 %s · 同水準 %d 位%s" % (
|
| 248 |
+
username, user_pp, engine, peers_n, (" · %.0f 秒" % elapsed) if elapsed is not None else "")]
|
| 249 |
+
head.append("樣本:top 榜 %d、打過沒進榜 %d(其中打過 ≤%d 次的 %d)、同儕互驗 %d%s" % (
|
| 250 |
+
len(top), len(extra), ATTEMPTS, len(few), len(peer_rows),
|
| 251 |
+
("、算不了 %d(%s)" % (n_err, err_top)) if n_err else "") + ("、沒趨勢可用 %d" % n_skip if n_skip else ""))
|
| 252 |
+
if not rows:
|
| 253 |
+
return "\n".join(head + ["樣本不夠,回測做不了喵(你的成績太少,或單圖成績查不到)。"])
|
| 254 |
+
body: List[str] = ["**你的成績(藏起來再預測)**"]
|
| 255 |
+
for label, rs in (("全部", rows), ("top 榜(你最好的那些,預測偏低才正常)", top), ("打過沒進榜(打了但沒打好)", extra),
|
| 256 |
+
("打過 ≤%d 次(主人定義的「3 次以內」)" % ATTEMPTS, few)):
|
| 257 |
+
ln = _line(label, rs, both=True)
|
| 258 |
+
if ln:
|
| 259 |
+
body.append(ln)
|
| 260 |
+
base = few if len(few) >= MIN_N * 2 else rows
|
| 261 |
+
base_name = "≤%d 次那批" % ATTEMPTS if base is few else "全部"
|
| 262 |
+
body.append("**按同儕人數**(%s;單次)" % base_name)
|
| 263 |
+
for b in ("0 人", "1 人", "2 人", "≥3 人"):
|
| 264 |
+
ln = _line(b, [r for r in base if _n_bucket(r["n"]) == b])
|
| 265 |
+
if ln:
|
| 266 |
+
body.append(ln)
|
| 267 |
+
body.append("**按 mods**(%s)" % base_name)
|
| 268 |
+
for mk in MODS_SHOW:
|
| 269 |
+
ln = _line(mk or "NM", [r for r in base if r["mkey"] == mk])
|
| 270 |
+
if ln:
|
| 271 |
+
body.append(ln)
|
| 272 |
+
other = [r for r in base if r["mkey"] not in MODS_SHOW]
|
| 273 |
+
ln = _line("其他 mods", other)
|
| 274 |
+
if ln:
|
| 275 |
+
body.append(ln)
|
| 276 |
+
body.append("**按星數**(帶 mods 的官方星數;%s)" % base_name)
|
| 277 |
+
for _lo, _hi, name in STAR_BANDS:
|
| 278 |
+
ln = _line(name, [r for r in base if _band(r["stars"]) == name])
|
| 279 |
+
if ln:
|
| 280 |
+
body.append(ln)
|
| 281 |
+
if peer_rows:
|
| 282 |
+
body.append("**同儕互驗**(把那個人藏起來預測他)")
|
| 283 |
+
ln = _line("全部", peer_rows, both=True)
|
| 284 |
+
if ln:
|
| 285 |
+
body.append(ln)
|
| 286 |
+
for b in ("1 人", "2 人", "≥3 人"):
|
| 287 |
+
ln = _line("其他同儕 " + b, [r for r in peer_rows if _n_bucket(r["n"]) == b])
|
| 288 |
+
if ln:
|
| 289 |
+
body.append(ln)
|
| 290 |
+
if feel:
|
| 291 |
+
sp = statistics.median(x["spread"] for x in feel)
|
| 292 |
+
bm = statistics.median(x["best_vs_median"] for x in feel)
|
| 293 |
+
body.append("**手感(lazer,同一張圖重打)**:%d 張、每張 %d 筆(中位);最好 vs 中位 +%.0f%%、全距 %.0f%%(都取中位)" % (
|
| 294 |
+
len(feel), int(statistics.median(x["n"] for x in feel)), bm * 100, sp * 100))
|
| 295 |
+
elif not user_lazer:
|
| 296 |
+
body.append("**手感**:你是 stable 玩家,API 只有每張圖最好的一筆,量不到重打的分散")
|
| 297 |
+
tail = ["-# 誤差=(預測−實際)÷實際;偏差=中位數(正=預測偏高)。3 次內=P(FC) 換成 1−(1−p)^%d。" % ATTEMPTS,
|
| 298 |
+
"-# 主人的目標:偏差 ±3% 內、分散不超過手感帶寬加一成。同儕人數 0=只靠你自己的趨勢。"]
|
| 299 |
+
return "\n".join(head + body + tail)
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
_LAST: Dict[str, Tuple[float, Dict[str, Any]]] = {}
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def run(client: Any, username: str, log: Callable[[str], None] = lambda s: None,
|
| 306 |
+
progress: Optional[Callable[[str], None]] = None, peers_n: int = F.PEERS_N) -> str:
|
| 307 |
+
t0 = time.time()
|
| 308 |
+
|
| 309 |
+
def say(text: str) -> None:
|
| 310 |
+
if progress:
|
| 311 |
+
progress(text)
|
| 312 |
+
say("讀取你的成績…")
|
| 313 |
+
u = client.user(username)
|
| 314 |
+
if u is None:
|
| 315 |
+
return "找不到玩家 **%s** 喵~" % username
|
| 316 |
+
uid, uname, upp = int(F._g(u, "id")), str(F._g(u, "username", default=username)), float(F._g(u, "pp", default=0.0) or 0.0)
|
| 317 |
+
user_scores = F.fetch_best(client, uid, F.USER_BEST_TTL)
|
| 318 |
+
if not user_scores:
|
| 319 |
+
return "**%s** 沒有 ranked 成績喵。" % uname
|
| 320 |
+
eng = F.pick_engine(client, user_scores, log, progress)
|
| 321 |
+
if eng["calc"] is None:
|
| 322 |
+
return "校準沒過,回測沒意義喵:\n" + F.engine_fail_text(uname, upp, eng)
|
| 323 |
+
calc, off = eng["calc"], eng["off"]
|
| 324 |
+
say("找同水準玩家…")
|
| 325 |
+
peer_ids, peer_scores, pstat = F.select_peers(client, u, user_scores, F.POOL_N, peers_n, progress, log)
|
| 326 |
+
if not peer_scores:
|
| 327 |
+
return "找不到跟 **%s** 同水準的玩家成績,回測做不了喵。" % uname
|
| 328 |
+
cands = F.aggregate(peer_scores, "any")
|
| 329 |
+
say("整理你的樣本…")
|
| 330 |
+
samples, plays = user_samples(client, uid, user_scores, log, progress)
|
| 331 |
+
keys = [(int(s["score"]["beatmap_id"]), s["score"]["mods"]) for s in samples]
|
| 332 |
+
if off is not None and str(eng["engine"]).startswith("官方"):
|
| 333 |
+
say("抓 %d 張圖的難度屬性…" % len(keys))
|
| 334 |
+
off.prefetch(keys, progress, "回測")
|
| 335 |
+
rows: List[Dict[str, Any]] = []
|
| 336 |
+
n_err, n_skip = 0, 0
|
| 337 |
+
err_kinds: Dict[str, int] = {}
|
| 338 |
+
for i, smp in enumerate(samples, 1):
|
| 339 |
+
s = smp["score"]
|
| 340 |
+
bid, mkey = int(s["beatmap_id"]), F.mods_key(s["mods"])
|
| 341 |
+
try:
|
| 342 |
+
r = predict_one(cands.get((bid, mkey)), user_scores, peer_scores, calc, bid, s["mods"], mkey, bool(s["lazer"]))
|
| 343 |
+
except Exception as e:
|
| 344 |
+
n_err += 1
|
| 345 |
+
k = "%s: %s" % (type(e).__name__, str(e)[:60])
|
| 346 |
+
err_kinds[k] = err_kinds.get(k, 0) + 1
|
| 347 |
+
continue
|
| 348 |
+
if not r:
|
| 349 |
+
n_skip += 1
|
| 350 |
+
continue
|
| 351 |
+
rows.append({"src": smp["src"], "plays": smp["plays"], "bid": bid, "mkey": mkey, "actual": float(s["pp"]),
|
| 352 |
+
"stars": r["stars"], "n": r["n"], "p_fc": r["p_fc"],
|
| 353 |
+
"e1": rel_err(r["exp1"], s["pp"]), "e3": rel_err(r["exp3"], s["pp"])})
|
| 354 |
+
if progress and i % 50 == 0:
|
| 355 |
+
progress("預測你的成績 %d/%d" % (i, len(samples)))
|
| 356 |
+
say("同儕互驗…")
|
| 357 |
+
peer_rows = peer_samples(cands, peer_scores, [(r["bid"], r["mkey"]) for r in rows], calc, progress=progress)
|
| 358 |
+
say("手感…")
|
| 359 |
+
feel = feel_samples(client, uid, samples, plays, bool(eng["user_lazer"]), log, progress)
|
| 360 |
+
err_top = ";".join("%s ×%d" % kv for kv in sorted(err_kinds.items(), key=lambda kv: -kv[1])[:2])
|
| 361 |
+
payload = dict(username=uname, user_pp=upp, rows=rows, peer_rows=peer_rows, feel=feel, engine=eng["engine"],
|
| 362 |
+
peers_n=len(peer_ids), n_err=n_err, n_skip=n_skip, err_top=err_top, elapsed=time.time() - t0,
|
| 363 |
+
user_lazer=bool(eng["user_lazer"]))
|
| 364 |
+
for k in {str(username).strip().lower(), uname.lower()}:
|
| 365 |
+
_LAST[k] = (time.time(), payload)
|
| 366 |
+
s_all = summarize([r["e1"] for r in rows])
|
| 367 |
+
s3 = summarize([r["e3"] for r in rows])
|
| 368 |
+
log("[osu 回測] %s:樣本 %d(top %d)、同儕互驗 %d、手感 %d 張、算不了 %d;單次 %s;3 次內偏差 %s;%.0f 秒" % (
|
| 369 |
+
uname, len(rows), sum(1 for r in rows if r["src"] == "top"), len(peer_rows), len(feel), n_err, fmt(s_all),
|
| 370 |
+
("%+.1f%%" % (s3["bias"] * 100)) if s3.get("n") else "—", time.time() - t0))
|
| 371 |
+
return format_report(**payload)
|
vb_osu_farm.py
CHANGED
|
@@ -889,6 +889,70 @@ class OfficialEngine:
|
|
| 889 |
return {"pp": r["pp"], "stars": r["stars"], "max_combo": r["max_combo"], "exact": exact}
|
| 890 |
|
| 891 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 892 |
# ── 主流程(client 鴨子型別:user/best/peers/osu_file[/attributes/beatmap_info]) ──
|
| 893 |
PAGE_TTL = 6 * 3600
|
| 894 |
_RESULTS: Dict[str, Tuple[float, Dict[str, Any]]] = {} # 整份精算結果留 6 小時:翻頁不用重算
|
|
@@ -939,57 +1003,11 @@ def run(client: Any, username: str, filt: str = "any", top_n: int = 10, peers_n:
|
|
| 939 |
log("[osu] %s:%d 筆 top 成績、總 pp %.0f" % (uname, len(user_scores), upp))
|
| 940 |
mark("成績")
|
| 941 |
|
| 942 |
-
# ── 引擎:① 官方公式移植 + 官方難度屬性(隨改版更新)② rosu-pp 備援 ──
|
| 943 |
-
|
| 944 |
-
|
| 945 |
-
tried: List[Tuple[str, Dict[str, Any]]] = []
|
| 946 |
-
calc: Optional[CalcFn] = None
|
| 947 |
-
calib: Dict[str, Any] = {}
|
| 948 |
-
engine = ""
|
| 949 |
-
notes: List[str] = []
|
| 950 |
-
off: Optional[OfficialEngine] = None
|
| 951 |
-
if hasattr(client, "attributes") and hasattr(client, "beatmap_info"):
|
| 952 |
-
say("校準 pp 引擎(你的 top %d)…" % CALIB_N)
|
| 953 |
-
off = OfficialEngine(client, user_lazer, log)
|
| 954 |
-
off.prefetch([(s["beatmap_id"], s["mods"]) for s in user_scores if s.get("pp")][:CALIB_N],
|
| 955 |
-
progress, "校準")
|
| 956 |
-
c_off = calibrate(user_scores, off.calc)
|
| 957 |
-
log("[osu] 校準(官方公式移植):n=%s 平均 %.2f%% 最大 %.2f%% ok=%s" % (
|
| 958 |
-
c_off["n"], c_off["mean_pct"] or -1, c_off["worst_pct"], c_off["ok"]))
|
| 959 |
-
for ln in calib_lines(c_off):
|
| 960 |
-
log("[osu] " + ln.strip())
|
| 961 |
-
tried.append(("官方公式移植", c_off))
|
| 962 |
-
if c_off["ok"]:
|
| 963 |
-
calc, calib, engine = off.calc, c_off, "官方公式移植+官方難度屬性"
|
| 964 |
-
if off.note():
|
| 965 |
-
notes.append(off.note())
|
| 966 |
-
if calc is None and PP.available():
|
| 967 |
-
cache: Dict[int, bytes] = {}
|
| 968 |
-
|
| 969 |
-
def rosu_calc(bid: int, mods: Any, acc: float, miss: int, combo: Optional[int], lazer: bool,
|
| 970 |
-
**kw: Any) -> Dict[str, Any]:
|
| 971 |
-
if bid not in cache:
|
| 972 |
-
cache[bid] = client.osu_file(bid)
|
| 973 |
-
return PP.calc(cache[bid], mods, acc, miss, combo, lazer, **kw)
|
| 974 |
-
c_rosu = calibrate(user_scores, rosu_calc)
|
| 975 |
-
log("[osu] 校準(rosu-pp %s):n=%s 平均 %.2f%% 最大 %.2f%% ok=%s" % (
|
| 976 |
-
PP.version(), c_rosu["n"], c_rosu["mean_pct"] or -1, c_rosu["worst_pct"], c_rosu["ok"]))
|
| 977 |
-
for ln in calib_lines(c_rosu):
|
| 978 |
-
log("[osu] " + ln.strip())
|
| 979 |
-
tried.append(("rosu-pp " + PP.version(), c_rosu))
|
| 980 |
-
if c_rosu["ok"]:
|
| 981 |
-
calc, calib, engine = rosu_calc, c_rosu, "rosu-pp " + PP.version()
|
| 982 |
if calc is None:
|
| 983 |
-
|
| 984 |
-
return "沒有可用的 pp 計算引擎喵(官方屬性端點與 rosu-pp 都不在)。"
|
| 985 |
-
# 用誤差較小的那個引擎的校準當報告主體,其餘引擎附一行
|
| 986 |
-
tried.sort(key=lambda t: (t[1]["mean_pct"] if t[1]["mean_pct"] is not None else 999.0))
|
| 987 |
-
name, best = tried[0]
|
| 988 |
-
others = ["-# 其他引擎:%s 平均誤差 %s%s" % (
|
| 989 |
-
n, ("%.2f%%" % c["mean_pct"]) if c["mean_pct"] is not None else "算不出",
|
| 990 |
-
("(%s)" % c["errors"]) if c.get("errors") else "")
|
| 991 |
-
for n, c in tried[1:]]
|
| 992 |
-
return format_report(uname, upp, [], best, filt, 0, top_n, name) + ("\n" + "\n".join(others) if others else "")
|
| 993 |
|
| 994 |
mark("校準")
|
| 995 |
say("找同水準玩家…")
|
|
|
|
| 889 |
return {"pp": r["pp"], "stars": r["stars"], "max_combo": r["max_combo"], "exact": exact}
|
| 890 |
|
| 891 |
|
| 892 |
+
# ── 引擎挑選(run 與 /osu backtest 共用)────────────────────────────
|
| 893 |
+
def pick_engine(client: Any, user_scores: List[Dict[str, Any]], log: Callable[[str], None] = lambda s: None,
|
| 894 |
+
progress: Optional[Callable[[str], None]] = None) -> Dict[str, Any]:
|
| 895 |
+
"""① 官方公式移植+官方難度屬性 ② rosu-pp 備援:兩個都先用主人自己的成績校準,誰過門檻用誰。
|
| 896 |
+
回 {calc, calib, engine, notes, off, tried, user_lazer};calc None=都不過(engine_fail_text 拿 tried 寫報告)。"""
|
| 897 |
+
def say(text: str) -> None:
|
| 898 |
+
if progress:
|
| 899 |
+
progress(text)
|
| 900 |
+
user_lazer = sum(1 for s in user_scores if s["lazer"]) * 2 >= len(user_scores)
|
| 901 |
+
tried: List[Tuple[str, Dict[str, Any]]] = []
|
| 902 |
+
calc: Optional[CalcFn] = None
|
| 903 |
+
calib: Dict[str, Any] = {}
|
| 904 |
+
engine = ""
|
| 905 |
+
notes: List[str] = []
|
| 906 |
+
off: Optional[OfficialEngine] = None
|
| 907 |
+
if hasattr(client, "attributes") and hasattr(client, "beatmap_info"):
|
| 908 |
+
say("校準 pp 引擎(你的 top %d)…" % CALIB_N)
|
| 909 |
+
off = OfficialEngine(client, user_lazer, log)
|
| 910 |
+
off.prefetch([(s["beatmap_id"], s["mods"]) for s in user_scores if s.get("pp")][:CALIB_N],
|
| 911 |
+
progress, "校準")
|
| 912 |
+
c_off = calibrate(user_scores, off.calc)
|
| 913 |
+
log("[osu] 校準(官方公式移植):n=%s 平均 %.2f%% 最大 %.2f%% ok=%s" % (
|
| 914 |
+
c_off["n"], c_off["mean_pct"] or -1, c_off["worst_pct"], c_off["ok"]))
|
| 915 |
+
for ln in calib_lines(c_off):
|
| 916 |
+
log("[osu] " + ln.strip())
|
| 917 |
+
tried.append(("官方公式移植", c_off))
|
| 918 |
+
if c_off["ok"]:
|
| 919 |
+
calc, calib, engine = off.calc, c_off, "官方公式移植+官方難度屬性"
|
| 920 |
+
if off.note():
|
| 921 |
+
notes.append(off.note())
|
| 922 |
+
if calc is None and PP.available():
|
| 923 |
+
cache: Dict[int, bytes] = {}
|
| 924 |
+
|
| 925 |
+
def rosu_calc(bid: int, mods: Any, acc: float, miss: int, combo: Optional[int], lazer: bool,
|
| 926 |
+
**kw: Any) -> Dict[str, Any]:
|
| 927 |
+
if bid not in cache:
|
| 928 |
+
cache[bid] = client.osu_file(bid)
|
| 929 |
+
return PP.calc(cache[bid], mods, acc, miss, combo, lazer, **kw)
|
| 930 |
+
c_rosu = calibrate(user_scores, rosu_calc)
|
| 931 |
+
log("[osu] 校準(rosu-pp %s):n=%s 平均 %.2f%% 最大 %.2f%% ok=%s" % (
|
| 932 |
+
PP.version(), c_rosu["n"], c_rosu["mean_pct"] or -1, c_rosu["worst_pct"], c_rosu["ok"]))
|
| 933 |
+
for ln in calib_lines(c_rosu):
|
| 934 |
+
log("[osu] " + ln.strip())
|
| 935 |
+
tried.append(("rosu-pp " + PP.version(), c_rosu))
|
| 936 |
+
if c_rosu["ok"]:
|
| 937 |
+
calc, calib, engine = rosu_calc, c_rosu, "rosu-pp " + PP.version()
|
| 938 |
+
return {"calc": calc, "calib": calib, "engine": engine, "notes": notes, "off": off, "tried": tried,
|
| 939 |
+
"user_lazer": user_lazer}
|
| 940 |
+
|
| 941 |
+
|
| 942 |
+
def engine_fail_text(uname: str, upp: float, eng: Dict[str, Any], filt: str = "any", top_n: int = 10) -> str:
|
| 943 |
+
"""兩個引擎都沒過門檻:用誤差較小的那個的校準當報告主體,其餘引擎附一行。"""
|
| 944 |
+
tried = list(eng.get("tried") or [])
|
| 945 |
+
if not tried:
|
| 946 |
+
return "沒有可用的 pp 計算引擎喵(官方屬性端點與 rosu-pp 都不在)。"
|
| 947 |
+
tried.sort(key=lambda t: (t[1]["mean_pct"] if t[1]["mean_pct"] is not None else 999.0))
|
| 948 |
+
name, best = tried[0]
|
| 949 |
+
others = ["-# 其他引擎:%s 平均誤差 %s%s" % (
|
| 950 |
+
n, ("%.2f%%" % c["mean_pct"]) if c["mean_pct"] is not None else "算不出",
|
| 951 |
+
("(%s)" % c["errors"]) if c.get("errors") else "")
|
| 952 |
+
for n, c in tried[1:]]
|
| 953 |
+
return format_report(uname, upp, [], best, filt, 0, top_n, name) + ("\n" + "\n".join(others) if others else "")
|
| 954 |
+
|
| 955 |
+
|
| 956 |
# ── 主流程(client 鴨子型別:user/best/peers/osu_file[/attributes/beatmap_info]) ──
|
| 957 |
PAGE_TTL = 6 * 3600
|
| 958 |
_RESULTS: Dict[str, Tuple[float, Dict[str, Any]]] = {} # 整份精算結果留 6 小時:翻頁不用重算
|
|
|
|
| 1003 |
log("[osu] %s:%d 筆 top 成績、總 pp %.0f" % (uname, len(user_scores), upp))
|
| 1004 |
mark("成績")
|
| 1005 |
|
| 1006 |
+
# ── 引擎:① 官方公式移植 + 官方難度屬性(隨改版更新)② rosu-pp 備援(pick_engine;/osu backtest 也用同一支)──
|
| 1007 |
+
eng = pick_engine(client, user_scores, log, progress)
|
| 1008 |
+
calc, calib, engine, notes, off = eng["calc"], eng["calib"], eng["engine"], eng["notes"], eng["off"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1009 |
if calc is None:
|
| 1010 |
+
return engine_fail_text(uname, upp, eng, filt, top_n)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1011 |
|
| 1012 |
mark("校準")
|
| 1013 |
say("找同水準玩家…")
|