Files
mtga/scripts/render_daily_html.py
T
fukunee 58446ec562 Add TRK set preview and refresh draft analysis
Track the TRK preview package and the newest value artifacts for FRA20261007, move the 17lands API notes under data, and ignore downloaded 17lands, card image and live directories.
2026-11-15 11:37:16 +08:00

179 lines
7.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python
"""按「双色色组 × 日期」统计每日胜率,渲染成折线图(只画胜率)。
数据:data/17lands/<snap>/drafts/event_details.jsonl(每局 completion_time + won)
+ trophies/trophies_index.jsonl(draft_id -> 我方色组)
色组:用 primary_pair 归到 10 个双色(单色/无归类丢弃)。
输出:value/<snap>/reports/daily.html
"""
from __future__ import annotations
import argparse
import json
import sys
from collections import defaultdict
from datetime import datetime, timezone
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT / "scripts"))
import _layout # noqa: E402
from render_templates_html import primary_pair # noqa: E402
PAIRS = ["WU", "UB", "BR", "RG", "WG", "WB", "BG", "UR", "UG", "WR"]
COLOR = {"WU": "#e8d76a", "UB": "#7cc4ff", "BR": "#e06a6a", "RG": "#e0956a",
"WG": "#8fe08f", "WB": "#c9c9cf", "BG": "#6ad0a0", "UR": "#b48cff",
"UG": "#5fd6cf", "WR": "#ff9f6a"}
def load_jsonl(p: Path):
if not p.exists():
return []
return [json.loads(l) for l in p.read_text(encoding="utf-8").splitlines() if l.strip()]
def build(snapshot: Path) -> dict:
colors = {r["aggregate_id"]: r.get("colors")
for r in load_jsonl(snapshot / "trophies/trophies_index.jsonl")}
# day -> pair -> [games, wins]
day = defaultdict(lambda: defaultdict(lambda: [0, 0]))
for rec in load_jsonl(snapshot / "drafts/event_details.jsonl"):
pair = primary_pair(colors.get(rec.get("draft_id")))
if pair not in PAIRS:
continue
for m in rec.get("details", {}).get("match_results") or []:
for g in m.get("game_results") or []:
ct = g.get("completion_time")
if not ct:
continue
d = datetime.fromtimestamp(int(ct), tz=timezone.utc).strftime("%Y-%m-%d")
day[d][pair][0] += 1
day[d][pair][1] += 1 if g.get("won") else 0
days = sorted(day)
series = []
for p in PAIRS:
pts = []
for d in days:
gg, ww = day[d].get(p, [0, 0])
if gg:
pts.append({"d": d, "g": gg, "w": ww, "wr": round(ww / gg, 4)})
if pts:
series.append({"pair": p, "points": pts})
# 全场每日
allp = []
for d in days:
gg = sum(v[0] for v in day[d].values())
ww = sum(v[1] for v in day[d].values())
allp.append({"d": d, "g": gg, "w": ww, "wr": round(ww / gg, 4)})
return {"days": days, "series": series, "all": allp,
"color": COLOR, "pairs": PAIRS}
HTML = r"""<!doctype html><html lang="zh"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>__SET__ · 色组每日走势</title><style>__LAYOUT_CSS__
.dash{max-width:1460px;margin:0 auto;padding:16px 20px}
.ctl{display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin:10px 0 4px}
.ctl button{background:#232b38;color:#cfd8e6;border:1px solid #33405a;border-radius:8px;padding:4px 12px;cursor:pointer}
.ctl button.on{background:#2f5f96;color:#fff;border-color:#2f5f96}
.leg{display:flex;gap:12px;flex-wrap:wrap;margin:8px 0}
.leg span{display:inline-flex;align-items:center;gap:5px;font-size:12px;cursor:pointer;padding:1px 4px;border-radius:5px}
.leg span.off{opacity:.3}
.leg i{width:12px;height:12px;border-radius:3px;display:inline-block}
svg text{fill:#c7d0de}
.tip{position:fixed;pointer-events:none;background:#0f1218;border:1px solid #33405a;border-radius:6px;
padding:6px 9px;font-size:12px;color:#e8e8ea;display:none;z-index:99}
.note{color:#8a94a6;font-size:12px}
</style></head><body>
__BANNER__
<div class="dash">
<h1>__SET__ · 双色色组每日走势</h1>
<p class="note">按 <code>completion_time</code>(UTC)分天,统计每个双色色组当天的<b>胜率</b>。样本均为 7 胜奖杯牌表,绝对胜率偏高(≈80%+),请看<b>相对变化</b>。</p>
<div class="ctl">
<span>显示:</span>
<button id="allbtn" data-all="1">全场</button>
</div>
<div class="leg" id="leg"></div>
<svg id="chart" width="1140" height="460"></svg>
</div>
<div class="tip" id="tip"></div>
__FOOTBANNER__
<script src="assets/d3.v7.min.js"></script>
<script>
const DATA=__DATA__;
let showAll=false;
const hidden=new Set();
const legend=document.getElementById("leg");
DATA.pairs.forEach(p=>{
const s=document.createElement("span"); s.dataset.p=p;
s.innerHTML='<i style="background:'+DATA.color[p]+'"></i>'+p;
s.onclick=()=>{ if(hidden.has(p))hidden.delete(p); else hidden.add(p); s.classList.toggle("off"); draw(); };
legend.appendChild(s);
});
document.getElementById("allbtn").onclick=e=>{showAll=!showAll;e.target.classList.toggle("on",showAll);draw();};
const W=1140,H=460,M={l:56,r:16,t:16,b:34};
const svg=d3.select("#chart"); const tip=document.getElementById("tip");
function draw(){
svg.selectAll("*").remove();
const xs=DATA.days.map(d=>new Date(d+"T00:00:00Z"));
const x=d3.scaleTime().domain(d3.extent(xs)).range([M.l,W-M.r]);
let allv=[]; DATA.series.forEach(s=>s.points.forEach(p=>allv.push(p.wr)));
if(showAll) DATA.all.forEach(p=>allv.push(p.wr));
let ymax=Math.min(1,d3.max(allv)*1.05);
let ymin=Math.max(0,d3.min(allv)*0.95);
const y=d3.scaleLinear().domain([ymin,ymax||1]).nice().range([H-M.b,M.t]);
const gx=svg.append("g").attr("transform","translate(0,"+(H-M.b)+")")
.call(d3.axisBottom(x).ticks(Math.min(DATA.days.length,10)).tickFormat(d3.timeFormat("%m-%d")));
const gy=svg.append("g").attr("transform","translate("+M.l+",0)")
.call(d3.axisLeft(y).tickFormat(v=>(v*100).toFixed(0)+"%"));
gx.selectAll("text").attr("fill","#c7d0de"); gy.selectAll("text").attr("fill","#c7d0de");
gx.selectAll("line").attr("stroke","#2a2e3a"); gy.selectAll("line").attr("stroke","#2a2e3a");
gy.selectAll(".domain").attr("stroke","#33405a"); gx.selectAll(".domain").attr("stroke","#33405a");
const line=d3.line().x(p=>x(new Date(p.d+"T00:00:00Z"))).y(p=>y(p.wr));
if(showAll){
svg.append("path").datum(DATA.all).attr("fill","none").attr("stroke","#fff")
.attr("stroke-width",2.4).attr("stroke-dasharray","5 3").attr("d",line);
}
DATA.series.forEach(s=>{
if(hidden.has(s.pair))return;
svg.append("path").datum(s.points).attr("fill","none").attr("stroke",DATA.color[s.pair])
.attr("stroke-width",2).attr("d",line);
svg.selectAll(".pt-"+s.pair).data(s.points).enter().append("circle")
.attr("cx",p=>x(new Date(p.d+"T00:00:00Z"))).attr("cy",p=>y(p.wr)).attr("r",3)
.attr("fill",DATA.color[s.pair])
.on("mousemove",(e,p)=>{tip.style.display="block";
tip.style.left=(e.clientX+12)+"px"; tip.style.top=(e.clientY+12)+"px";
tip.innerHTML=s.pair+" · "+p.d+"<br>局数 "+p.g+" · 胜 "+p.w+"<br>胜率 "+(p.wr*100).toFixed(1)+"%";})
.on("mouseleave",()=>tip.style.display="none");
});
}
draw();
</script>
</body></html>
"""
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--snapshot", required=True)
ap.add_argument("--out", required=True)
a = ap.parse_args()
data = build(Path(a.snapshot))
out = Path(a.out) / "reports" / "daily.html"
_layout.SET = _layout.set_of(a.out)
out.parent.mkdir(parents=True, exist_ok=True)
_layout.ensure_assets(out.parent)
html = (HTML.replace("__DATA__", json.dumps(data, ensure_ascii=False))
.replace("__SET__", _layout.SET)
.replace("__LAYOUT_CSS__", _layout.CSS)
.replace("__BANNER__", _layout.banner("daily.html"))
.replace("__FOOTBANNER__", _layout.footbanner(
"按天统计(UTC);游标悬停看当天局数/胜场/胜率。样本 = 7 胜奖杯牌表,绝对胜率偏高。")))
out.write_text(html, encoding="utf-8")
print(f"wrote {out} ({len(data['days'])} 天, {len(data['series'])} 个色组)")
return 0
if __name__ == "__main__":
raise SystemExit(main())