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.
996 lines
49 KiB
Python
996 lines
49 KiB
Python
#!/usr/bin/env python3
|
||
"""Render the archetype templates as an HTML view.
|
||
|
||
Combines:
|
||
value/<SNAPSHOT>/templates/*.json (parameters + evidence)
|
||
value/<SNAPSHOT>/templates/_members.json (cluster -> draft ids)
|
||
data/17lands/<SNAPSHOT>/drafts/event_details.jsonl (game results)
|
||
data/mtgch/image-en|image-cn/*.webp (card art, EN/CN)
|
||
|
||
Output: value/<SNAPSHOT>/reports/templates/index.html + <slug>.html
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import html
|
||
import json
|
||
import math
|
||
import os
|
||
import re
|
||
import sys
|
||
from collections import Counter, defaultdict
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||
import _layout # noqa: E402
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
|
||
|
||
def load_jsonl(path: Path):
|
||
with path.open(encoding="utf-8") as fh:
|
||
for line in fh:
|
||
line = line.strip()
|
||
if line:
|
||
yield json.loads(line)
|
||
|
||
|
||
def slugify(s):
|
||
return re.sub(r"[^A-Za-z0-9]+", "_", s or "").strip("_")
|
||
|
||
|
||
def primary_pair(colors):
|
||
if not colors:
|
||
return None
|
||
order = "WUBRG"
|
||
up = [c for c in colors if c in order] # uppercase = main colors
|
||
low = [c for c in colors.upper() if c in order] # all colors
|
||
if len(up) >= 2:
|
||
pair = up[:2]
|
||
elif len(up) == 1:
|
||
pair = [up[0]] + [c for c in low if c != up[0]][:1]
|
||
else:
|
||
pair = low[:2]
|
||
if not pair:
|
||
return None
|
||
return "".join(sorted(pair, key=order.index))
|
||
def esc(s):
|
||
return html.escape(str(s)) if s is not None else ""
|
||
|
||
|
||
# --- rank filter: keep Gold and above, drop Bronze / Silver ---
|
||
RANK_ORDER = {"Bronze": 0, "Silver": 1, "Gold": 2, "Platinum": 3, "Diamond": 4, "Mythic": 5}
|
||
RANK_MIN = 2 # Gold
|
||
|
||
|
||
def rank_ok(s):
|
||
return RANK_ORDER.get((s or "").split("-")[0], 99) >= RANK_MIN
|
||
|
||
|
||
BASIC_LANDS = {"Plains", "Island", "Swamp", "Mountain", "Forest", "Wastes"}
|
||
|
||
COLOR_HEX = {"W": "#f7c948", "U": "#3b82f6", "B": "#8b5cf6", "R": "#ef4444", "G": "#22c55e"}
|
||
|
||
PAIR_DESC = {
|
||
"WU": "白蓝 = Fatehold 学院的「观察快攻」。用观察/预知(surveil/scry)精选牌库,按曲线铺高效生物,靠飞行、警戒的小生物持续施压,属于节奏型快攻。学院备咒是 Peer Review(造 Cadet 衍生物并观察1)。",
|
||
"UB": "蓝黑 = Theorix 学院的「坟场算术」。用大量自磨(mill)把牌堆进坟场、尽快达到 threshold,再把坟场当第二种手牌,靠回收与坟场收益打中后期价值。学院备咒是 Omit Variables(磨三张)。",
|
||
"BR": "红黑 = Stingerquill 学院的「直伤烧脸」。一边用手牌直接打对手血量,一边把‘对对手造成伤害’转化成自己场面的强化——越打越疼。学院备咒是 Vicious Verse(对对手造成1点伤害)。",
|
||
"RG": "红绿 = Konstrari 学院的「法力爆冲」。用 Heartwood 令牌(红绿法术力)跳费,快速到达高费,用超大生物和 ramp 收益压死对手。学院备咒是 Soul Tether(造一个 Heartwood)。",
|
||
"WG": "白绿 = Vigorbloom 学院的「回血成长」。靠 +1/+1 指示物和回血把生物越养越大、血越堆越多,用成长型生物在中后期碾压。学院备咒是 Seed Suture(给生物+1/+1 并回1血)。",
|
||
"WB": "白黑 = Liliana 的「消耗战」。从坟场不断回收小生物反复铺场,用源源不断的小威胁和资源消耗慢慢磨死对手。",
|
||
"UR": "蓝红 = Chandra 的「咒语热力」。围绕施放非生物咒语(热力/prowess、每当你施放…)触发收益,靠瞬间与法术打节奏、保持压力。",
|
||
"BG": "黑绿 = Garruk 的「兽群」。主打大生物,靠死触+践踏突破防线,中后期用身材和交换优势压死对手。",
|
||
"WR": "白红 = Ajani 的「军团」。用 +1/+1 指示物和增益快速把生物做大,然后全力进攻的快攻。",
|
||
"UG": "蓝绿 = Jace 的「掌控」。围绕 Empower Jace,持续制造/充能 Jace 鹏洛客,用过牌和赋予鹏洛客异能滚出资源与胜局。",
|
||
}
|
||
|
||
|
||
def desc_for(t):
|
||
if t.get("description_zh"):
|
||
return t["description_zh"]
|
||
base = PAIR_DESC.get(t.get("archetype"), "")
|
||
cr = (t.get("deck_params") or {}).get("creature_ratio") or 0
|
||
if cr >= 0.62:
|
||
style = "这套偏生物铺场"
|
||
elif cr >= 0.52:
|
||
style = "这套生物与咒语较均衡"
|
||
else:
|
||
style = "这套偏法术/节奏"
|
||
defs = "、".join(t.get("defining_cards", [])[:3])
|
||
tags = []
|
||
for c in t.get("cards", []):
|
||
for tg in (c.get("mechanic_tags") or []):
|
||
if tg not in tags:
|
||
tags.append(tg)
|
||
tail = f"本簇(n={t.get('n_decks')}){style}"
|
||
if defs:
|
||
tail += f",区分于其他变体的关键牌是 {defs}"
|
||
if tags:
|
||
tail += f",机制上围绕 {' / '.join(tags[:2])}"
|
||
tail += "。"
|
||
return base + " " + tail
|
||
|
||
|
||
def load_cn_names(mtgch: Path) -> dict:
|
||
f = mtgch / "cardnames-zh-CN.txt"
|
||
out = {}
|
||
if f.exists():
|
||
for line in f.open(encoding="utf-8"):
|
||
parts = line.rstrip("\n").split("|")
|
||
if len(parts) >= 2 and parts[0] and parts[1] and parts[1] != parts[0]:
|
||
out[parts[0]] = parts[1]
|
||
return out
|
||
|
||
|
||
SET = "FRA" # 由 build() 从 out_dir 名推导覆盖
|
||
|
||
|
||
def build(snapshot: Path, out_dir: Path, mtgch: Path, report_dir: Path) -> None:
|
||
global SET
|
||
_sm = re.match(r"([A-Za-z]+)", out_dir.name)
|
||
SET = (_sm.group(1) if _sm else "FRA").upper()
|
||
_layout.ensure_assets(report_dir.parent if report_dir.name == "templates" else report_dir)
|
||
tdir = out_dir / "templates"
|
||
rel = os.path.relpath(mtgch, report_dir).replace("\\", "/")
|
||
rel_img_en = f"{rel}/image-en"
|
||
rel_img_cn = f"{rel}/image-cn"
|
||
# 本地卡图缓存(新系列用 fetch_card_images.py 下载)
|
||
_ci_dir = ROOT / "data" / "card_images" / SET
|
||
rel_img_ci = os.path.relpath(_ci_dir, report_dir).replace("\\", "/")
|
||
|
||
# 17lands 全场色组数据(color_ratings.json)
|
||
pair17: dict = {}
|
||
_crf = snapshot / "stats/color_ratings.json"
|
||
if _crf.exists():
|
||
for r in json.loads(_crf.read_text(encoding="utf-8")):
|
||
sn = r.get("short_name")
|
||
g = r.get("games") or 0
|
||
if not r.get("is_summary") and isinstance(sn, str) and len(sn) == 2 and g:
|
||
pair17[sn] = (r["wins"] / g, g)
|
||
|
||
# id -> name
|
||
cards = json.loads((snapshot / "stats/card_data.json").read_text(encoding="utf-8"))["data"]
|
||
id2name = {c["mtga_id"]: c["name"] for c in cards}
|
||
cdata = {c["name"]: c for c in cards}
|
||
card_url = {c["name"]: c.get("url") for c in cards}
|
||
global _IIH, _STAT_POP
|
||
_STAT_POP = _build_stat_pop(cards)
|
||
_IIH = {}
|
||
for _c in cards:
|
||
_a, _b = _c.get("ever_drawn_win_rate"), _c.get("never_drawn_win_rate")
|
||
if _a is not None and _b is not None:
|
||
_IIH[_c["name"]] = _a - _b
|
||
for rec in load_jsonl(snapshot / "drafts/draft_picks.jsonl"):
|
||
for cid, m in (rec.get("cards") or {}).items():
|
||
id2name.setdefault(int(cid), m.get("name"))
|
||
card_url.setdefault(m.get("name"), m.get("image_url"))
|
||
|
||
def img(name, lang):
|
||
sl = slugify(name).lower()
|
||
if sl:
|
||
# 1) 本地卡图缓存(data/card_images/<SET>/<slug>.<ext>)
|
||
for _ext in ("webp", "jpg", "jpeg", "png"):
|
||
if (_ci_dir / f"{sl}.{_ext}").exists():
|
||
return f"{rel_img_ci}/{sl}.{_ext}"
|
||
# 2) mtgch 本地卡库
|
||
p = mtgch / f"image-{lang}" / sl[0] / f"{sl}.full.webp"
|
||
if p.exists():
|
||
return f"{rel_img_en if lang == 'en' else rel_img_cn}/{sl[0]}/{sl}.full.webp"
|
||
if lang == "cn":
|
||
pe = mtgch / "image-en" / sl[0] / f"{sl}.full.webp"
|
||
if pe.exists():
|
||
return f"{rel_img_en}/{sl[0]}/{sl}.full.webp"
|
||
return card_url.get(name) # 远程兑底(17lands / Scryfall)
|
||
|
||
cn_names = load_cn_names(mtgch)
|
||
|
||
# game results per draft_id
|
||
games_by_draft: dict[str, list] = defaultdict(list)
|
||
ev = snapshot / "drafts/event_details.jsonl"
|
||
if ev.exists():
|
||
for rec in load_jsonl(ev):
|
||
for m in rec.get("details", {}).get("match_results") or []:
|
||
for g in m.get("game_results") or []:
|
||
if not rank_ok(g.get("start_rank")):
|
||
continue
|
||
games_by_draft[rec["draft_id"]].append({
|
||
"won": bool(g.get("won")), "on_play": g.get("on_play"),
|
||
"turns": g.get("total_turns"), "opp": primary_pair(g.get("opponent_colors")),
|
||
"mull": g.get("mulligans") or 0,
|
||
})
|
||
|
||
members = json.loads((tdir / "_members.json").read_text(encoding="utf-8"))
|
||
draft_rec = {}
|
||
deck_full = {}
|
||
for d in load_jsonl(snapshot / "trophies/trophies_decks.jsonl"):
|
||
if not rank_ok(d.get("start_rank")):
|
||
continue
|
||
draft_rec[d["aggregate_id"]] = (d["wins"], d["losses"])
|
||
cc = Counter()
|
||
for e in d["maindeck"]:
|
||
nm = id2name.get(e["mtga_id"])
|
||
if nm:
|
||
cc[nm] += e["count"]
|
||
deck_full[d["aggregate_id"]] = {"rec": f"{d['wins']}-{d['losses']}",
|
||
"colors": d.get("colors") or "",
|
||
"cards": sorted(cc.items())}
|
||
templates = []
|
||
for f in tdir.glob("*.PremierDraft.*.json"):
|
||
templates.append(json.loads(f.read_text(encoding="utf-8")))
|
||
templates.sort(key=lambda t: (t["archetype"], -t["n_decks"]))
|
||
|
||
report_dir.mkdir(parents=True, exist_ok=True)
|
||
for t in templates:
|
||
slug = t["archetype_slug"]
|
||
gl = []
|
||
for did in members.get(slug, []):
|
||
gl.extend(games_by_draft.get(did, []))
|
||
wins = sum(1 for g in gl if g["won"])
|
||
n = len(gl) or 1
|
||
rec = wins / n
|
||
onp = [g for g in gl if g["on_play"] is True]
|
||
dfp = [g for g in gl if g["on_play"] is False]
|
||
op_wr = (sum(1 for g in onp if g["won"]) / len(onp)) if onp else 0
|
||
df_wr = (sum(1 for g in dfp if g["won"]) / len(dfp)) if dfp else 0
|
||
turns = [g["turns"] for g in gl if g["turns"]]
|
||
avg_turns = sum(turns) / len(turns) if turns else 0
|
||
mull = sum(g["mull"] for g in gl) / n
|
||
drafts = [draft_rec[d] for d in members.get(slug, []) if d in draft_rec]
|
||
dn = len(drafts) or 1
|
||
dr_avg = sum(w / (w + l) for w, l in drafts) / dn if drafts else 0
|
||
dr_70 = sum(1 for w, l in drafts if l == 0) / dn if drafts else 0
|
||
opp = defaultdict(lambda: [0, 0])
|
||
for g in gl:
|
||
o = g["opp"] or "?"
|
||
opp[o][0] += 1
|
||
opp[o][1] += 1 if g["won"] else 0
|
||
|
||
t["_game"] = {"n": len(gl), "wr": rec, "op_wr": op_wr, "df_wr": df_wr,
|
||
"avg_turns": avg_turns, "mull": mull, "drafts": dn,
|
||
"draft_record": dr_avg, "seven0": dr_70,
|
||
"matchups": sorted(((k, v[0], v[1] / v[0]) for k, v in opp.items()),
|
||
key=lambda x: -x[1])}
|
||
write_detail(t, slug, img, id2name, report_dir, rel, cn_names,
|
||
members.get(slug, []), deck_full, cdata)
|
||
write_index(templates, report_dir, pair17)
|
||
keep = {f"{t['archetype_slug']}.html" for t in templates} | {"index.html"}
|
||
for f in report_dir.glob("*.html"):
|
||
if f.name not in keep:
|
||
f.unlink()
|
||
print(f"rendered {len(templates)} template pages -> {report_dir}")
|
||
|
||
|
||
_IIH = {}
|
||
_STAT_POP = {}
|
||
|
||
|
||
def donut_svg(items, size=88, thick=13):
|
||
"""items: list of (hex, frac, label) -> SVG 圆环图。"""
|
||
r = (size - thick) / 2
|
||
circ = 2 * math.pi * r
|
||
cx = cy = size / 2
|
||
segs = []
|
||
off = 0.0
|
||
for col, frac, lab in items:
|
||
if frac <= 0:
|
||
continue
|
||
dash = frac * circ
|
||
segs.append(
|
||
f'<circle cx="{cx}" cy="{cy}" r="{r:.2f}" fill="none" stroke="{col}" stroke-width="{thick}" '
|
||
f'stroke-dasharray="{dash:.2f} {circ - dash:.2f}" stroke-dashoffset="{-off:.2f}" '
|
||
f'transform="rotate(-90 {cx} {cy})"><title>{esc(lab)}</title></circle>')
|
||
off += dash
|
||
return (f'<svg class="donut" width="{size}" height="{size}" viewBox="0 0 {size} {size}">'
|
||
f'{"".join(segs)}</svg>')
|
||
|
||
|
||
def _build_stat_pop(cards):
|
||
import statistics as _st
|
||
|
||
def ser(vals):
|
||
vals = [v for v in vals if v is not None]
|
||
if len(vals) < 5:
|
||
return None
|
||
return (_st.mean(vals), _st.pstdev(vals), len(vals), sorted(vals))
|
||
|
||
def iih(c):
|
||
a, b = c.get("ever_drawn_win_rate"), c.get("never_drawn_win_rate")
|
||
return (a - b) if (a is not None and b is not None) else None
|
||
|
||
return {
|
||
"alsa": ser([c.get("avg_seen") for c in cards]),
|
||
"ata": ser([c.get("avg_pick") for c in cards]),
|
||
"gp_wr": ser([c.get("win_rate") for c in cards]),
|
||
"oh_wr": ser([c.get("opening_hand_win_rate") for c in cards]),
|
||
"gd_wr": ser([c.get("drawn_win_rate") for c in cards]),
|
||
"gih_wr": ser([c.get("ever_drawn_win_rate") for c in cards]),
|
||
"gns_wr": ser([c.get("never_drawn_win_rate") for c in cards]),
|
||
"iwd": ser([c.get("drawn_improvement_win_rate") for c in cards]),
|
||
"iih": ser([iih(c) for c in cards]),
|
||
}
|
||
|
||
|
||
def _mv(metric, v):
|
||
if metric == "ata":
|
||
return f"{v:.2f}"
|
||
if metric == "alsa":
|
||
return f"{v:.1f}"
|
||
if metric in ("iih", "iwd"):
|
||
return f"{v*100:+.1f}%"
|
||
return f"{v*100:.1f}%"
|
||
|
||
|
||
def _mv_sd(metric, sd):
|
||
if metric == "ata":
|
||
return f"{sd:.2f}"
|
||
if metric == "alsa":
|
||
return f"{sd:.1f}"
|
||
return f"{sd*100:.1f}%"
|
||
|
||
|
||
def _metric_html(metric, v, label=None):
|
||
"""17lands 风格:数值 + 离群箭头(≥1.5σ) + 悬停弹窗(排名/z/均值/标准差)。"""
|
||
if v is None:
|
||
return "-"
|
||
txt = _mv(metric, v)
|
||
s = _STAT_POP.get(metric)
|
||
if not s:
|
||
return esc(txt)
|
||
m, sd, n, vals = s
|
||
z = (v - m) / sd if sd else 0.0
|
||
rank = sum(1 for x in vals if x > v) + 1
|
||
lab = f"{label} " if label else ""
|
||
tip = (f"{lab}{txt}\n排名 {rank}/{n}\nz-score {z:+.2f}(均值 {_mv(metric, m)} · 标准差 {_mv_sd(metric, sd)})")
|
||
return f'<span title="{esc(tip)}">{esc(txt)}</span>'
|
||
|
||
|
||
def land_tile(name, img, count, cn_names):
|
||
"""minimal card tile for a land (image + xN badge + name)."""
|
||
en = img(name, "en")
|
||
cn = img(name, "cn")
|
||
imgs = ""
|
||
if en:
|
||
imgs += f'<img class="ci en" loading="lazy" src="{en}" alt="{esc(name)}">'
|
||
if cn:
|
||
imgs += f'<img class="ci cn" loading="lazy" src="{cn}" alt="{esc(name)}">'
|
||
if not en and not cn:
|
||
imgs = '<div class="ci placeholder">no image</div>'
|
||
badge = f'<div class="dcnt">×{count}</div>' if count > 1 else ''
|
||
return (f'<div class="card rarity-land"><div class="imgwrap">{imgs}{badge}</div>'
|
||
f'<div class="cbody"><div class="cname">{esc(name)}</div></div></div>')
|
||
|
||
|
||
def card_tile(c, img, id2name, cn_names, deck_count=None):
|
||
en = img(c["name"], "en")
|
||
cn = img(c["name"], "cn")
|
||
tc = c["target_copies"]
|
||
cw = c.get("expected_copies")
|
||
if cw is None:
|
||
cw = c.get("target_copies") or 0
|
||
cd = c.get("context_delta")
|
||
cd_s = "-" if cd is None else f"{cd:+.3f}"
|
||
cd_cls = "" if cd is None else ("ctx-pos" if cd > 0 else "ctx-neg")
|
||
tags = " ".join(f"<span class=tg>{esc(t)}</span>" for t in (c.get("mechanic_tags") or []))
|
||
roles = " ".join(esc(r) for r in (c.get("roles") or []))
|
||
syn = ", ".join(esc(id2name.get(s["mtga_id"], s["mtga_id"])) for s in (c.get("synergy") or [])[:3])
|
||
imgs = ""
|
||
if en:
|
||
imgs += f'<img class="ci en" loading="lazy" src="{en}" alt="{esc(c["name"])}">'
|
||
if cn:
|
||
imgs += f'<img class="ci cn" loading="lazy" src="{cn}" alt="{esc(c["name"])}">'
|
||
if not en and not cn:
|
||
imgs = '<div class="ci placeholder">no image</div>'
|
||
cid = c.get("mtga_id")
|
||
cn = cn_names.get(c["name"])
|
||
rarity = (c.get("rarity") or "").lower()
|
||
badge = f'<div class="dcnt">×{deck_count}</div>' if deck_count else ''
|
||
_ia = c.get("inclusion_adj")
|
||
_ir = c.get("inclusion")
|
||
_orf = c.get("offer_rate")
|
||
inc_v = _ia if _ia is not None else _ir
|
||
inc_raw = "" # raw inclusion no longer shown on the tile (kept in the tooltip)
|
||
_is_land = c.get("roles") == ["land"]
|
||
_ln = (c.get("play_num") if _is_land else c.get("cast_num")) or 0
|
||
_lg = c.get("cast_den") or 0
|
||
_lpg = (c.get("play_games") if _is_land else c.get("cast_games")) or 0
|
||
_llab = "地" if _is_land else "施放"
|
||
use_part = f"{_lpg/_lg*100:.0f}%" if _lg >= 5 else "—" # >=5 replay games, else sample too small
|
||
inc_tip = f"带牌/见过 = {pct(_ia)}(原始采纳率 {pct(_ir)}"
|
||
if _orf is not None:
|
||
inc_tip += f";见过率 {pct(_orf)}"
|
||
inc_tip += ")"
|
||
if _lg:
|
||
inc_tip += (f";{_llab}率:{_lpg}/{_lg} 局至少施放一次(共 {_ln} 次;REPLAY 实测)"
|
||
+ (" ※ 不足 5 局,不予显示" if _lg < 5 else ""))
|
||
return f"""<div class="card rarity-{rarity}">
|
||
<div class="imgwrap">{imgs}{badge}<div class="ovl">IIH {_metric_html("iih", _IIH.get(c.get("name")))} / ALSA {_metric_html("alsa", c.get("alsa"))}</div></div>
|
||
<div class="cbody">
|
||
<div class="cname">{esc(c["name"])}</div>
|
||
<div class="crow"><span class="tc" title="预期牌张:理想 40 张中的期望张数(0–2)">{cw:.2f}</span>
|
||
<span class="inc" title="{esc(inc_tip)}">{pct(inc_v)}/{use_part}</span></div>
|
||
<div class="stats">Δ <span class="{cd_cls}">{cd_s}</span> · signal {c.get("signal") if c.get("signal") is not None else "—"} · prio {c.get("pick_priority")} · n={c.get("cluster_sample_games")}</div>
|
||
<div class="tags">{tags}</div>
|
||
{f'<div class="syn">syn: {syn}</div>' if syn else ''}
|
||
<div class="roles-foot">{roles}</div>
|
||
</div></div>"""
|
||
|
||
|
||
def pct(v):
|
||
return "-" if v is None else f"{v*100:.0f}%"
|
||
|
||
|
||
def _ctag(raw, img, cdata):
|
||
"""[[Card]] or [[Card|label]] -> clickable tag."""
|
||
nm, _, label = raw.partition("|")
|
||
nm, label = nm.strip(), (label or raw).strip()
|
||
c = cdata.get(nm) or {}
|
||
src = img(nm, "en") or ""
|
||
if not src and nm not in cdata:
|
||
return f"<b>{esc(label)}</b>" # not a known card -> plain text
|
||
rr = (c.get("rarity") or "common").lower()
|
||
return (f'<span class="ctag" data-name="{esc(nm)}" data-img="{esc(src)}" data-rar="{esc(rr)}"'
|
||
f' title="点击看大图">{esc(label)}</span>')
|
||
|
||
|
||
def _md_inline(s, img, cdata):
|
||
"""[[Card Name]] -> clickable card tag; **bold** -> <b>."""
|
||
out, i, n = [], 0, len(s)
|
||
while i < n:
|
||
j1, j2 = s.find("[[", i), s.find("**", i)
|
||
cands = [x for x in (j1, j2) if x >= 0]
|
||
if not cands:
|
||
out.append(esc(s[i:]))
|
||
break
|
||
j = min(cands)
|
||
out.append(esc(s[i:j]))
|
||
if j == j1:
|
||
b = s.find("]]", j + 2)
|
||
if b < 0:
|
||
out.append(esc(s[j:]))
|
||
break
|
||
out.append(_ctag(s[j + 2:b], img, cdata))
|
||
i = b + 2
|
||
else:
|
||
b = s.find("**", j + 2)
|
||
if b < 0:
|
||
out.append(esc(s[j:]))
|
||
break
|
||
out.append("<b>" + esc(s[j + 2:b]) + "</b>")
|
||
i = b + 2
|
||
return "".join(out)
|
||
|
||
|
||
def render_guide(text, img, cdata):
|
||
out = []
|
||
for para in (text or "").split(chr(10) + chr(10)):
|
||
para = para.strip()
|
||
if para:
|
||
out.append("<p>" + _md_inline(para, img, cdata) + "</p>")
|
||
return "".join(out)
|
||
|
||
|
||
def desc_html(t):
|
||
import re as _re
|
||
return _re.sub(r"\*\*(.+?)\*\*", r"<strong>\1</strong>", esc(desc_for(t)))
|
||
|
||
|
||
def fmt(v, nd=3):
|
||
return "-" if v is None else (f"{v:.{nd}f}" if isinstance(v, float) else str(v))
|
||
|
||
|
||
def l17(c):
|
||
return (f'IWD {_metric_html("iwd", c.get("iwd"))} · ATA {_metric_html("ata", c.get("ata"))} · PR {pct(c.get("play_rate"))}')
|
||
|
||
|
||
def gih1(v):
|
||
return "-" if v is None else f"{v*100:.1f}%"
|
||
|
||
|
||
def num1(v):
|
||
return "-" if v is None else f"{v:.1f}"
|
||
|
||
|
||
def write_detail(t, slug, img, id2name, report_dir, rel, cn_names, deck_ids=None, deck_full=None, cdata=None):
|
||
dp = t["deck_params"]
|
||
nonland_all = [c for c in t["cards"] if c.get("roles") != ["land"]]
|
||
def _inc(c):
|
||
a = c.get("inclusion_adj")
|
||
return a if a is not None else (c.get("inclusion") or 0)
|
||
|
||
def _use(c):
|
||
"""REPLAY 实测使用率:咒语=施放次数/局,地=落场次数/局。无数据返回 -1。"""
|
||
n = (c.get("play_num") if c.get("roles") == ["land"] else c.get("cast_num")) or 0
|
||
d = c.get("cast_den") or 0
|
||
return (n / d) if d else -1.0
|
||
|
||
def _keep(c):
|
||
if _inc(c) < 0.10:
|
||
return False
|
||
# 有 replay 覆盖(≥20 局)却一次都没施放/落场的,剔除
|
||
if (c.get("cast_den") or 0) >= 20 and _use(c) <= 0:
|
||
return False
|
||
return True
|
||
|
||
nonland = [c for c in nonland_all if _keep(c)]
|
||
|
||
def _ec(c):
|
||
v = c.get("expected_copies")
|
||
return v if v is not None else (c.get("target_copies") or 0)
|
||
|
||
nonland.sort(key=_ec, reverse=True)
|
||
lands = [c for c in t["cards"] if c.get("roles") == ["land"]]
|
||
g = t["_game"]
|
||
curve = dp["curve_targets"]
|
||
cmax = max(curve.values()) or 1
|
||
curve_html = "".join(
|
||
f'<div class="bar"><div class="barfill" style="height:{v/cmax*100:.0f}%"></div>'
|
||
f'<div class="barlab">{k}</div><div class="barval">{v:.1f}</div></div>'
|
||
for k, v in curve.items())
|
||
cw = dp["color_weights"]
|
||
cw_items = sorted(((COLOR_HEX.get(k, "#ddd"), v, f"{k} {v*100:.0f}%") for k, v in cw.items()),
|
||
key=lambda x: "WUBRG".find(x[2][0]))
|
||
cw_donut = donut_svg(cw_items)
|
||
# 基本地按颜色汇总成百分比
|
||
_LC = {"Plains": "W", "Island": "U", "Swamp": "B", "Mountain": "R", "Forest": "G"}
|
||
_blc: dict = {}
|
||
for _n, _v in (dp.get("basic_lands") or {}).items():
|
||
_c = _LC.get(_n)
|
||
if _c:
|
||
_blc[_c] = _blc.get(_c, 0) + (_v or 0)
|
||
_blt = sum(_blc.values()) or 1
|
||
bl_items = sorted(((COLOR_HEX.get(_c, "#ddd"), _blc[_c] / _blt, f"{_c} {_blc[_c]/_blt*100:.0f}%") for _c in _blc),
|
||
key=lambda x: "WUBRG".find(x[2][0]))
|
||
bl_donut = donut_svg(bl_items)
|
||
def _mxcol(k, cnt, wr):
|
||
col = "#4ad07a" if wr >= 0.5 else "#e06a6a"
|
||
return (f'<div class="mxb" title="{esc(k)}:我方 {wr*100:.0f}%({cnt} 局)">'
|
||
f'<div class="mxbar"><div class="mxfill2" style="height:{wr*100:.1f}%;background:{col}"></div></div>'
|
||
f'<div class="mxl">{esc(k)}</div><div class="mxv">{wr*100:.0f}%</div></div>')
|
||
# 只显示对手「双色」对位(单色/未分类不显示)
|
||
_PAIRS_OK = {"WU", "UB", "BR", "RG", "WG", "WB", "BG", "UR", "UG", "WR"}
|
||
mu_cols = "".join(_mxcol(k, cnt, wr) for k, cnt, wr in
|
||
sorted(g["matchups"], key=lambda x: -x[1])
|
||
if k in _PAIRS_OK)
|
||
defmap = {c["name"]: c for c in nonland_all}
|
||
defining = [defmap[nm] for nm in t.get("defining_cards", []) if nm in defmap][:6]
|
||
if not defining:
|
||
defining = nonland[:6]
|
||
creatures = [c for c in nonland if "creature" in (c.get("roles") or [])]
|
||
spells = [c for c in nonland if "creature" not in (c.get("roles") or [])]
|
||
tiles_c = "".join(card_tile(c, img, id2name, cn_names) for c in creatures)
|
||
tiles_s = "".join(card_tile(c, img, id2name, cn_names) for c in spells)
|
||
key_html = "".join(card_tile(c, img, id2name, cn_names) for c in defining)
|
||
aff = [defmap[nm] for nm in (t.get("signal_cards") or t.get("affinity_cards") or []) if nm in defmap][:8]
|
||
aff_html = "".join(card_tile(c, img, id2name, cn_names) for c in aff)
|
||
# 信号牌 = 看到它就决定进这个思路的程度(抓位越早 + 抽到提升越大);无则隐藏
|
||
aff_section = ("<h2>信号牌(看到就进这个思路)</h2>\n<div class=\"grid\">%s</div>" % aff_html) if aff_html else ""
|
||
# reference deck
|
||
ref = None
|
||
_mtga = ""
|
||
_rp = report_dir.parent.parent / "reference_decks" / f"{slug}.json"
|
||
if _rp.exists():
|
||
ref = json.loads(_rp.read_text(encoding="utf-8"))
|
||
if ref:
|
||
_byname = {c["name"]: c for c in t["cards"]}
|
||
_tiles = "".join(card_tile(_byname[d["name"]], img, id2name, cn_names,
|
||
deck_count=(d["count"] if d["count"] > 1 else None))
|
||
for d in ref["spells"] if d["name"] in _byname)
|
||
# non-basic lands: full card tiles (with inc / expected copies / n), then basic lands last
|
||
_litems = sorted(ref["lands"].items(), key=lambda kv: -kv[1])
|
||
_tiles += "".join(card_tile(_byname[_nm], img, id2name, cn_names,
|
||
deck_count=(_v if _v > 1 else None))
|
||
for _nm, _v in _litems if _nm in _byname)
|
||
_tiles += "".join(land_tile(_nm, img, _v, cn_names)
|
||
for _nm, _v in _litems if _nm not in _byname and _nm in BASIC_LANDS)
|
||
_used = ref.get("rarity_used", {})
|
||
_lands = " · ".join(f"{v}× {k}" for k, v in sorted(ref["lands"].items(), key=lambda kv: -kv[1]))
|
||
_mtga = "\n".join(["Deck"] + [f"{d['count']} {d['name']}" for d in ref["spells"]]
|
||
+ [f"{v} {k}" for k, v in sorted(ref["lands"].items(), key=lambda kv: -kv[1])])
|
||
ref_html = f'<div class="grid">{_tiles}</div>'
|
||
else:
|
||
ref_html = '<p class="legend">(未生成典型套牌)</p>'
|
||
# every deck in this cluster, click to expand the 40-card list
|
||
deck_full = deck_full or {}
|
||
_medoid = (ref or {}).get("spells") and t.get("reference_deck", {}).get("aggregate_id")
|
||
deck_ids = [d for d in (deck_ids or []) if d in deck_full]
|
||
deck_ids.sort(key=lambda d: -sum(deck_full[d]["rec"].split("-")[0].isdigit() and int(deck_full[d]["rec"].split("-")[0]) or 0
|
||
for _ in [0]))
|
||
rows = []
|
||
for d in deck_ids:
|
||
info = deck_full[d]
|
||
mine = " · 代表牌表" if d == _medoid else ""
|
||
_bn = {c["name"]: c for c in t["cards"]}
|
||
_pill = {c["name"]: (c.get("expected_copies") or 0) for c in t["cards"]}
|
||
|
||
def _grp(nm):
|
||
if nm in BASIC_LANDS:
|
||
return 2 # basic lands last
|
||
if (_bn.get(nm, {}).get("roles") or []) == ["land"]:
|
||
return 1 # then non-basic lands
|
||
return 0 # spells first
|
||
|
||
_cards = sorted(info["cards"], key=lambda x: (_grp(x[0]), -_pill.get(x[0], 0), x[0]))
|
||
_mtga_d = chr(10).join(["Deck"] + [f"{c} {nm}" for nm, c in _cards])
|
||
_parts = []
|
||
for _nm, _c in _cards:
|
||
_src = img(_nm, "en") or ""
|
||
_rr = ((_bn.get(_nm) or {}).get("rarity") or ("land" if _nm in BASIC_LANDS else "common")).lower()
|
||
_badge = f'<i class="mn">×{_c}</i>' if _c > 1 else ""
|
||
_parts.append(f'<span class="mwrap"><img class="mini" loading="lazy" src="{_src}"'
|
||
f' data-name="{esc(_nm)}" data-rar="{esc(_rr)}" alt="{esc(_nm)}"'
|
||
f' title="{esc(_nm)}">{_badge}</span>')
|
||
mini = "".join(_parts)
|
||
cols = [COLOR_HEX[ch] for ch in info["colors"].upper() if ch in COLOR_HEX] or ["#2a3240"]
|
||
n = len(cols)
|
||
stops = ",".join(f"{c} {int(100*i/n)}% {int(100*(i+1)/n)}%" for i, c in enumerate(cols))
|
||
rows.append(
|
||
f'<div class="dcell"><div class="dhead" style="--g:linear-gradient(135deg,{stops})"'
|
||
f' data-deck="{esc(_mtga_d)}" onclick="copyDeck(this)" title="点击复制该副 MTGA 牌表">'
|
||
f'<b>{esc(info["rec"])}</b><span class="dcol">{esc(info["colors"])}</span>'
|
||
f'<span class="dmeta">{sum(c for _, c in info["cards"])} 张{mine}'
|
||
f'<i class="dcopy">⧉ 复制</i></span></div>'
|
||
f'<div class="minicards">{mini}</div></div>')
|
||
decks_html = (f'<h2>簇内牌表({len(deck_ids)} 副)</h2><div class="decks">{"".join(rows)}</div>'
|
||
if rows else '<h2>簇内牌表</h2><p class="legend">(无)</p>')
|
||
guide_html = ('<h2>攻略</h2><div class="guide">'
|
||
+ render_guide(t.get("guide_zh"), img, cdata or {}) + '</div>') if t.get("guide_zh") else ""
|
||
beh_html = ('<h2>实战数据(replay)</h2><div class="guide">'
|
||
+ render_guide(t.get("behavior_zh"), img, cdata or {}) + '</div>') if t.get("behavior_zh") else ""
|
||
land_tiles = "".join(card_tile(c, img, id2name, cn_names) for c in lands)
|
||
|
||
doc = f"""<!doctype html><html lang="zh"><head><meta charset="utf-8">
|
||
<meta name="viewport" content="width=device-width,initial-scale=1">
|
||
<title>{esc(t['archetype_name'])} · {SET}</title>
|
||
<style>{CSS}</style></head><body class="show-en">
|
||
{_banner('<label class="toggle"><input type="checkbox" id="lang"> 中文卡图</label>')}
|
||
<main class="wrap">
|
||
<h1>{esc(t['archetype_name'])}</h1>
|
||
<div class="meta">archetype <b>{esc(t.get('colors') or t['archetype'])}</b> · slug <code>{esc(slug)}</code> ·
|
||
<span title="核心子集:确实在打这个思路的牌表(带了 ≥ 一半定义牌),所有指标的统计分母">核心牌表</span> <b>{t['n_decks']}</b> / <span title="KMeans 在同一色对内分出的整个簇大小(含未达标牌表)">簇 {t.get('cluster_size', '-')}</span> 副 ·
|
||
<span title="这些核心牌表打过的对局总数">{g['n']} 局</span> ·
|
||
<span title="样本置信度 = min(1, 核心副数 / 150)">confidence</span> {t['confidence']} ·
|
||
<span title="KMeans 轮廓系数:越接近 1 越分得开;本格式普遍很低(~0.02–0.04)">silhouette</span> {t.get('silhouette', '-')}</div>
|
||
<p class="playstyle">{desc_html(t)}</p>
|
||
{guide_html}
|
||
{beh_html}
|
||
<div class="panel">
|
||
<div class="kv"><span>地</span><b>{dp['land_count']}</b></div>
|
||
<div class="kv"><span>生物比</span><b>{dp['creature_ratio']*100:.0f}%</b></div>
|
||
<div class="kv"><span>单局胜率</span><b>{g['wr']*100:.1f}%</b></div>
|
||
<div class="kv"><span>先手胜率</span><b>{g['op_wr']*100:.1f}%</b></div>
|
||
<div class="kv"><span>后手胜率</span><b>{g['df_wr']*100:.1f}%</b></div>
|
||
<div class="kv"><span>平均回合</span><b>{g['avg_turns']/2:.1f}</b></div>
|
||
<div class="kv"><span>平均调度</span><b>{g['mull']:.2f}</b></div>
|
||
<div class="curve">{curve_html}</div>
|
||
<div class="legend" style="margin:-2px 0 8px">每根柱 = 该思路核心牌表的平均张数(费用 1/2/3/4/5/6+,共 23 张咒语);
|
||
advisor 配牌时以 <b>2 / 7 / 6 / 4 / 3 / 1</b> 的完美基线打底、再按这条均值浮动。</div>
|
||
<div class="dons">
|
||
<div class="donutwrap">{cw_donut}<span class="cwl">颜色</span></div>
|
||
<div class="donutwrap">{bl_donut}<span class="cwl">基本地</span></div>
|
||
</div>
|
||
<div class="mxwrap"><div class="mxcap">对位胜率 vs 对手双色(绿=高于50%)</div><div class="mxcol">{mu_cols}</div></div>
|
||
</div>
|
||
<h2>定义牌</h2>
|
||
<div class="grid">{key_html}</div>
|
||
{aff_section}
|
||
<h2>典型套牌 <button type="button" class="copybtn" data-deck="{esc(_mtga)}" onclick="copyDeck(this)">一键复制牌表(MTGA)</button></h2>
|
||
{ref_html}
|
||
<h2>生物</h2>
|
||
<div class="grid">{tiles_c}</div>
|
||
<h2>咒语 / 其他</h2>
|
||
<div class="grid">{tiles_s}</div>
|
||
<h2>非基本地</h2>
|
||
<div class="grid">{land_tiles}</div>
|
||
{decks_html}
|
||
</main>
|
||
{_footbanner(DETAIL_LEGEND)}
|
||
<div class="preview" id="preview">
|
||
<img id="preview-img" alt="">
|
||
<div class="pcap" id="preview-cap"></div>
|
||
</div>
|
||
<script>
|
||
{COPY_JS}
|
||
document.querySelectorAll('.card').forEach(function(card){{
|
||
card.addEventListener('click', function(e){{
|
||
e.stopPropagation();
|
||
var cn = document.body.classList.contains('show-cn');
|
||
var img = card.querySelector(cn ? '.ci.cn' : '.ci.en') || card.querySelector('.ci');
|
||
if (!img || img.classList.contains('placeholder')) return;
|
||
document.getElementById('preview-img').src = img.src;
|
||
var nm = card.querySelector('.cname');
|
||
document.getElementById('preview-cap').textContent = nm ? nm.textContent : '';
|
||
var rm = (card.className.match(/rarity-([a-z]+)/) || [])[1];
|
||
var RC = {{mythic:'#e0673a', rare:'#c9a34a', uncommon:'#9aa7b0', common:'#414a59', land:'#5f8f6f', special:'#a06ad0', bonus:'#a06ad0'}};
|
||
var col = RC[rm] || '#2a2e3a';
|
||
var pv = document.getElementById('preview');
|
||
pv.style.borderColor = col;
|
||
pv.style.boxShadow = '0 14px 40px #000c, 0 0 0 2px ' + col + '66';
|
||
pv.style.display = 'block';
|
||
}});
|
||
}});
|
||
document.querySelectorAll('.ctag').forEach(function(tg){{
|
||
tg.addEventListener('click', function(e){{
|
||
e.stopPropagation();
|
||
var RC3 = {{mythic:'#e0673a', rare:'#c9a34a', uncommon:'#9aa7b0', common:'#414a59', land:'#5f8f6f', special:'#a06ad0', bonus:'#a06ad0'}};
|
||
var col3 = RC3[tg.dataset.rar] || '#2a2e3a';
|
||
var pv3 = document.getElementById('preview');
|
||
document.getElementById('preview-img').src = tg.dataset.img;
|
||
document.getElementById('preview-cap').textContent = tg.dataset.name;
|
||
pv3.style.borderColor = col3;
|
||
pv3.style.boxShadow = '0 14px 40px #000c, 0 0 0 2px ' + col3 + '66';
|
||
pv3.style.display = 'block';
|
||
}});
|
||
}});
|
||
document.querySelectorAll('.mini').forEach(function(im){{
|
||
im.addEventListener('click', function(e){{
|
||
e.stopPropagation();
|
||
var RC2 = {{mythic:'#e0673a', rare:'#c9a34a', uncommon:'#9aa7b0', common:'#414a59', land:'#5f8f6f', special:'#a06ad0', bonus:'#a06ad0'}};
|
||
var col2 = RC2[im.dataset.rar] || '#2a2e3a';
|
||
var pv2 = document.getElementById('preview');
|
||
document.getElementById('preview-img').src = im.src;
|
||
document.getElementById('preview-cap').textContent = (im.dataset.name || im.alt) +
|
||
(im.parentElement.querySelector('.mn') ? ' ' + im.parentElement.querySelector('.mn').textContent : '');
|
||
pv2.style.borderColor = col2;
|
||
pv2.style.boxShadow = '0 14px 40px #000c, 0 0 0 2px ' + col2 + '66';
|
||
pv2.style.display = 'block';
|
||
}});
|
||
}});
|
||
document.addEventListener('click', function(e){{
|
||
if (e.target.closest('.card') || e.target.closest('.mini') || e.target.closest('.ctag') || e.target.closest('#preview')) return;
|
||
document.getElementById('preview').style.display = 'none';
|
||
}});
|
||
const c=document.getElementById('lang');
|
||
c.addEventListener('change',function(){{document.body.classList.toggle('show-cn',c.checked);document.body.classList.toggle('show-en',!c.checked);}});
|
||
</script>
|
||
</body></html>"""
|
||
(report_dir / f"{slug}.html").write_text(doc, encoding="utf-8")
|
||
|
||
|
||
def write_index(templates, report_dir, pair17=None):
|
||
pair17 = pair17 or {}
|
||
rows = ""
|
||
for t in templates:
|
||
if (t.get("archetype_name") or "").endswith("(其他)"):
|
||
continue
|
||
dp = t["deck_params"]
|
||
g = t["_game"]
|
||
turns_rounds = g["avg_turns"] / 2 # MTGA total_turns 是双方各自回合相加,敌我各一次=1 回合
|
||
_pair = t.get("archetype") or ""
|
||
_pw, _pg = pair17.get(_pair, (None, 0))
|
||
_p17 = f"{_pw*100:.1f}%" if _pw is not None else "—"
|
||
_p17tip = f"17lands 全场 {_pair} 色组:{_p17}({_pg} 局)" if _pw is not None else "17lands 无数据"
|
||
rows += (f'<tr>'
|
||
f'<td data-v="{esc(t["archetype_name"])}"><a href="{esc(t["archetype_slug"])}.html">{esc(t["archetype_name"])}</a></td>'
|
||
f'<td data-v="{t["n_decks"]}" title="核心牌表:确实在打这个思路(带了 ≥ 一半定义牌)的牌表数">{t["n_decks"]}</td>'
|
||
f'<td data-v="{t.get("cluster_size") or 0}" title="簇大小:KMeans 在同一色对内分出的整个簇(含未达标牌表)">{t.get("cluster_size", "-")}</td>'
|
||
f'<td data-v="{dp["creature_ratio"]}">{dp["creature_ratio"]*100:.0f}%</td>'
|
||
f'<td data-v="{g["wr"]:.4f}">{g["wr"]*100:.1f}%</td>'
|
||
f'<td data-v="{(_pw if _pw is not None else -1):.4f}" title="{esc(_p17tip)}">{esc(_pair)} {_p17}</td>'
|
||
f'<td data-v="{turns_rounds:.2f}">{turns_rounds:.1f}</td>'
|
||
f'<td class="desc">{desc_html(t)}</td></tr>')
|
||
doc = f"""<!doctype html><html lang="zh"><head><meta charset="utf-8">
|
||
<title>{SET} 模板视图</title><style>{CSS}</style></head><body>
|
||
{_banner()}
|
||
<main class="wrap">
|
||
<h1>{SET} PremierDraft · 子流派模板视图</h1>
|
||
|
||
<table class="idx"><thead><tr>
|
||
<th data-t="s">archetype</th><th data-t="n" title="核心牌表(统计分母)">核心数</th><th data-t="n" title="整个聚类簇大小(含未达标)">簇数</th>
|
||
<th data-t="n">生物比</th><th data-t="n">胜率</th><th data-t="n">17lands色组</th><th data-t="n">回合</th><th data-t="s">打法</th>
|
||
</tr></thead><tbody>{rows}</tbody></table>
|
||
</main>
|
||
{_footbanner('<span class="legend">胜率 = 本奖杯样本(偏高);17lands色组 = 该双色在 17lands 全场的胜率</span>')}
|
||
<script>
|
||
document.querySelectorAll('table.idx th').forEach((th, i) => {{
|
||
th.addEventListener('click', () => {{
|
||
const tb = document.querySelector('table.idx tbody');
|
||
const rows = [...tb.rows];
|
||
const asc = th.dataset.dir !== 'asc';
|
||
th.dataset.dir = asc ? 'asc' : 'desc';
|
||
document.querySelectorAll('table.idx th').forEach(o => {{ if (o !== th) o.removeAttribute('data-dir'); }});
|
||
rows.sort((a, b) => {{
|
||
const av = a.cells[i].dataset.v ?? a.cells[i].innerText;
|
||
const bv = b.cells[i].dataset.v ?? b.cells[i].innerText;
|
||
const an = parseFloat(av), bn = parseFloat(bv);
|
||
const r = (!isNaN(an) && !isNaN(bn)) ? (an - bn) : String(av).localeCompare(String(bv));
|
||
return asc ? r : -r;
|
||
}});
|
||
rows.forEach(r => tb.appendChild(r));
|
||
}});
|
||
}});
|
||
</script>
|
||
</body></html>"""
|
||
(report_dir / "index.html").write_text(doc, encoding="utf-8")
|
||
|
||
|
||
COPY_JS = """
|
||
function copyDeck(btn){
|
||
const text = btn.dataset.deck || '';
|
||
const old = btn.innerHTML;
|
||
const done = () => { btn.innerHTML = '<b>已复制 ✓</b>'; setTimeout(() => { btn.innerHTML = old; }, 1200); };
|
||
const legacy = () => {
|
||
const ta = document.createElement('textarea');
|
||
ta.value = text; ta.style.position = 'fixed'; ta.style.opacity = '0';
|
||
document.body.appendChild(ta); ta.focus(); ta.select();
|
||
try { document.execCommand('copy'); done(); } catch (e) { alert('复制失败,请手动选择牌表'); }
|
||
document.body.removeChild(ta);
|
||
};
|
||
if (navigator.clipboard && window.isSecureContext) {
|
||
navigator.clipboard.writeText(text).then(done).catch(legacy);
|
||
} else { legacy(); }
|
||
}
|
||
"""
|
||
|
||
def _banner(extra: str = "") -> str:
|
||
return ('<header class="banner"><div class="bwrap">'
|
||
f'<a class="brand" href="index.html">{SET} PremierDraft · 子流派模板</a>'
|
||
'<nav class="nav">'
|
||
'<a href="index.html">首页</a>'
|
||
'<a href="../daily.html">每日走势</a>'
|
||
'<a href="../matchups.html">克制矩阵</a>'
|
||
'<a href="../card_graph.html">牌间关系图</a>'
|
||
'<a href="../cluster_viz.html">聚类可视化</a>'
|
||
f'</nav>{extra}</div></header>')
|
||
|
||
|
||
_DETAIL_LEGEND_ITEMS = [
|
||
("蓝标", "预期牌张:该簇核心牌表里这张牌的平均张数(0–2,<1 可要可不要、≥1 必要)"),
|
||
("inc", "修正采纳率(带牌 / 见过) / 施放率(次·局;地为落场)"),
|
||
("signal", "信号强度(0–1):看到它多早、多确定地决定进这个思路 = 0.6×抓位分 + 0.4×抽到提升分"),
|
||
("prio", "抓牌优先级:本簇按 signal 从高到低的排名(1 = 最先拿)"),
|
||
("n", "该牌在本簇核心牌组里的对局样本数(cluster_sample_games)"),
|
||
("IIH", "起手即在手时的胜率"),
|
||
("ALSA", "平均第几手还能看到它"),
|
||
("Δ", "本簇 GIH 与奖杯基线的差(样本 <20 局显示 -)"),
|
||
]
|
||
DETAIL_LEGEND = "<br>".join("<b>%s</b> = %s" % (k, v) for k, v in _DETAIL_LEGEND_ITEMS)
|
||
|
||
|
||
def _footbanner(extra: str = "") -> str:
|
||
return f'<footer class="banner bot"><div class="footwrap">{extra}</div></footer>' if extra else ""
|
||
|
||
|
||
CSS = """*{box-sizing:border-box} body{font-family:system-ui,'Segoe UI',sans-serif;margin:0;padding:0;
|
||
background:#12141a;color:#e8e8ea}
|
||
.wrap{max-width:1460px;margin:0 auto;padding:20px 20px 8px}
|
||
.banner{background:#0f1218;border-bottom:1px solid #232b38}
|
||
.banner.bot{border-bottom:0;border-top:1px solid #232b38;margin-top:26px}
|
||
.bwrap{max-width:1460px;margin:0 auto;padding:10px 20px;display:flex;align-items:center;gap:18px;font-size:13px;flex-wrap:wrap}
|
||
.brand{font-weight:700;color:#fff}
|
||
.banner .nav{display:flex;gap:14px;margin-left:auto;flex-wrap:wrap}
|
||
.banner .nav a{color:#9fb0c7}
|
||
.banner .nav a:hover{color:#fff}
|
||
.toggle{color:#9fb0c7;white-space:nowrap}
|
||
.footwrap{max-width:1460px;margin:0 auto;padding:10px 20px;font-size:12px;color:#8a94a6;line-height:1.9;overflow-wrap:anywhere;word-break:break-word}
|
||
.footwrap b{color:#c7d0de}
|
||
a{color:#7cc4ff;text-decoration:none} h1{margin:.2em 0} h2{margin-top:1.4em;border-bottom:1px solid #2a2e3a;padding-bottom:.2em}
|
||
.topbar{display:flex;justify-content:space-between;align-items:center;font-size:14px}
|
||
.foot{margin-top:28px;padding-top:12px;border-top:1px solid #2a2e3a}
|
||
.foot .legend{margin:0}
|
||
.meta,.basics{color:#9aa2b1;font-size:13px;margin:.4em 0}
|
||
.panel{display:flex;gap:18px;flex-wrap:wrap;align-items:flex-end;background:#1b1e27;border:1px solid #2a2e3a;
|
||
border-radius:10px;padding:12px 16px;margin:10px 0}
|
||
.kv{display:flex;flex-direction:column;font-size:12px;color:#9aa2b1}.kv b{font-size:18px;color:#fff}
|
||
.curve{display:flex;gap:6px;align-items:flex-end;height:80px}
|
||
.curve.big{height:130px}
|
||
.bar{display:flex;flex-direction:column;align-items:center;justify-content:flex-end;width:30px;height:100%}
|
||
.barfill{width:100%;background:linear-gradient(#4a90d9,#2f5f96);border-radius:4px 4px 0 0;min-height:2px}
|
||
.barlab{font-size:11px;color:#9aa2b1}.barval{font-size:10px;color:#c9d1e0}
|
||
.cws{display:flex;gap:6px;align-items:center}
|
||
.cwl{font-size:11px;color:#9aa2b1}
|
||
.dons{display:flex;gap:14px;align-items:flex-end}
|
||
.donutwrap{display:flex;flex-direction:column;align-items:center;gap:3px}
|
||
.donut{display:block}
|
||
.cw{color:#111;font-weight:600;font-size:12px;padding:3px 8px;border-radius:6px}
|
||
.grid{display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:12px;margin-top:10px}
|
||
@media(max-width:1300px){.grid{grid-template-columns:repeat(6,minmax(0,1fr))}}
|
||
@media(max-width:1000px){.grid{grid-template-columns:repeat(4,minmax(0,1fr))}}
|
||
@media(max-width:700px){.grid{grid-template-columns:repeat(3,minmax(0,1fr))}}
|
||
.card{background:#1b1e27;border:1px solid #2a2e3a;border-radius:10px;overflow:hidden;display:flex;flex-direction:column}
|
||
.card.rarity-mythic{border-color:#e0673a;box-shadow:0 0 0 1px #e0673a55}
|
||
.card.rarity-rare{border-color:#c9a34a;box-shadow:0 0 0 1px #c9a34a44}
|
||
.card.rarity-uncommon{border-color:#9aa7b0;box-shadow:0 0 0 1px #9aa7b033}
|
||
.card.rarity-common{border-color:#414a59}
|
||
.card.rarity-land{border-color:#5f8f6f}
|
||
.card.rarity-special,.card.rarity-bonus{border-color:#a06ad0}
|
||
.imgwrap{position:relative;aspect-ratio:488/680;background:#0c0e13}
|
||
.ovl{position:absolute;left:6px;bottom:6px;background:rgba(0,0,0,.74);color:#fff;font-size:11px;padding:2px 6px;border-radius:6px;font-variant-numeric:tabular-nums;letter-spacing:.2px}
|
||
.dcnt{position:absolute;right:6px;top:6px;background:#2f5f96;color:#fff;font-weight:800;font-size:13px;padding:1px 8px;border-radius:8px;box-shadow:0 2px 6px #00000066}
|
||
.ci{width:100%;height:100%;object-fit:cover;display:block}
|
||
body.show-en .cn{display:none} body.show-cn .en{display:none}
|
||
.placeholder{display:flex;align-items:center;justify-content:center;color:#555;font-size:12px}
|
||
.cbody{padding:8px 10px}
|
||
.cname{font-weight:600;font-size:13px;line-height:1.2;min-height:2.4em}
|
||
.cnname{font-size:12px;color:#c9a34a;margin-top:-2px}
|
||
.preview{display:none;position:fixed;right:1.25rem;bottom:1.25rem;z-index:1000;background:#0c0e13;border:1px solid #2a2e3a;border-radius:1.6rem;padding:0.75rem;box-shadow:0 14px 40px #000c;max-width:52vw}
|
||
.preview img{width:min(520px,46vw);display:block;border-radius:1.1rem}
|
||
.preview .pcap{color:#c7d2e0;font-size:0.85rem;margin-top:0.5rem;text-align:center;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
||
.crow{display:flex;align-items:center;gap:6px;margin:4px 0}
|
||
.tc{background:#2f5f96;color:#fff;font-weight:700;border-radius:6px;padding:1px 7px;font-size:13px}
|
||
.rl{font-size:11px;color:#9aa2b1}.imp{font-size:11px;color:#c9a34a}
|
||
.lab{font-size:10px;color:#8a94a6}
|
||
.inc{font-size:11px;color:#9fd0ff;background:#16243a;border-radius:6px;padding:1px 6px;margin-left:auto}
|
||
.draw{font-size:11px;color:#c9e6b0;background:#172616;border-radius:6px;padding:1px 6px}
|
||
.mm{font-size:11px;color:#8fbfff;background:#1a2740;border-radius:6px;padding:1px 6px}
|
||
.stats{font-size:11px;color:#9aa2b1}
|
||
.seventeen{font-size:10px;color:#9fb0c7;margin-top:3px;letter-spacing:.2px}
|
||
.tags{display:flex;flex-wrap:wrap;gap:4px;margin-top:4px}
|
||
.tg{background:#262b38;color:#a9d0ff;font-size:10px;padding:1px 6px;border-radius:10px}
|
||
.syn{font-size:10px;color:#7f8aa0;margin-top:3px}
|
||
.roles-foot{font-size:10px;color:#8a94a6;margin-top:5px;padding-top:4px;border-top:1px solid #232838;text-transform:lowercase}
|
||
.ctx-pos{color:#4ad07a}.ctx-neg{color:#e06a6a}
|
||
table{border-collapse:collapse;width:100%;font-size:13px}
|
||
th,td{text-align:left;padding:6px 8px;border-bottom:1px solid #2a2e3a}
|
||
.mu td:first-child{font-weight:600}
|
||
.mbar{background:#262b38;border-radius:4px;height:10px;overflow:hidden}
|
||
.mbar>div{height:100%;background:#4a90d9}
|
||
.mx2{display:flex;flex-direction:column;gap:5px;margin-top:8px;max-width:640px}
|
||
.mxrow{display:flex;align-items:center;gap:10px;font-size:12px}
|
||
.mxopp{width:3.5em;font-weight:600}
|
||
.mxtrack{position:relative;flex:1;height:12px;background:#262b38;border-radius:6px}
|
||
.mxmid{position:absolute;left:50%;top:-2px;bottom:-2px;width:1px;background:#5a6478}
|
||
.mxfill{position:absolute;top:0;bottom:0;border-radius:6px}
|
||
.mxval{width:3.2em;text-align:right;font-variant-numeric:tabular-nums}
|
||
.mxn{width:4.5em;text-align:right;color:#8a94a6}
|
||
.mxwrap{display:flex;flex-direction:column;gap:4px}
|
||
.mxcap{font-size:11px;color:#9aa2b1}
|
||
.mxcol{display:flex;gap:6px;align-items:flex-end;height:80px}
|
||
.mxb{display:flex;flex-direction:column;align-items:center;width:30px;height:100%}
|
||
.mxbar{position:relative;width:100%;flex:1;display:flex;align-items:flex-end;background:#141821;border-radius:4px;overflow:hidden}
|
||
.mxbar:after{content:'';position:absolute;left:0;right:0;bottom:50%;height:1px;background:#5a6478;opacity:.7}
|
||
.mxfill2{width:100%;border-radius:4px 4px 0 0}
|
||
.mxl{font-size:10px;color:#9aa2b1;margin-top:2px}
|
||
.mxv{font-size:9px;color:#c9d1e0}
|
||
.decks{display:flex;flex-direction:column;gap:8px;margin-top:8px}
|
||
.dcell{border:1px solid #232b38;border-radius:8px;overflow:hidden;background:#151a22}
|
||
.dhead{display:flex;flex-direction:row;align-items:center;gap:10px;color:#eef2f8;font-size:13px;cursor:pointer;
|
||
padding:6px 12px;background-image:linear-gradient(rgba(12,14,19,.86),rgba(12,14,19,.86)),var(--g)}
|
||
.dhead b{min-width:36px}
|
||
.dhead .dcol{color:#b9c3d3;font-size:11px}
|
||
.dhead .dmeta{margin-left:auto;color:#8a94a6;font-size:11px;display:flex;align-items:center;gap:8px}
|
||
.dhead:hover{filter:brightness(1.18)}
|
||
.dcopy{font-style:normal;color:#9fb0c7;font-size:11px;opacity:.85}
|
||
.minicards{display:flex;flex-wrap:nowrap;gap:3px;padding:7px;overflow-x:auto}
|
||
.mwrap{position:relative;flex:0 0 auto}
|
||
.mini{width:42px;aspect-ratio:488/680;object-fit:cover;border-radius:4px;background:#0c0e13;cursor:pointer;display:block}
|
||
.mn{position:absolute;right:0;top:0;background:#2f5f96;color:#fff;font-size:9px;font-style:normal;font-weight:700;
|
||
padding:0 3px;border-radius:0 4px 0 6px}
|
||
.dcell .decklist{margin:0;border-radius:0;border:0;border-top:1px solid #232b38}
|
||
.lands{display:flex;flex-wrap:wrap;gap:8px}
|
||
.lt{background:#1b1e27;border:1px solid #2a2e3a;border-radius:6px;padding:4px 8px;font-size:12px}
|
||
.idx .kc{color:#9aa2b1;font-size:12px}
|
||
table.idx th{cursor:pointer;user-select:none;white-space:nowrap}
|
||
table.idx th::after{content:' ⇅';opacity:.35;font-size:11px}
|
||
table.idx th[data-dir=asc]::after{content:' ▲';opacity:1}
|
||
table.idx th[data-dir=desc]::after{content:' ▼';opacity:1}
|
||
table.idx td.desc{max-width:560px;font-size:12px;color:#c7cfdd;line-height:1.4}
|
||
.guide{background:#141821;border:1px solid #232b38;border-radius:10px;padding:2px 16px;margin:10px 0}
|
||
.guide p{margin:.7em 0;line-height:1.8;font-size:14px;color:#dbe2ec}
|
||
.ctag{display:inline-block;background:#1b2740;color:#9fd0ff;border-radius:6px;padding:0 6px;margin:0 1px;cursor:pointer;border-bottom:1px solid #2f5f96;font-size:13px}
|
||
.ctag:hover{background:#26406b;color:#fff}
|
||
.playstyle{background:#1b1e27;border-left:3px solid #c9a34a;padding:8px 12px;border-radius:6px;color:#d7dee9;font-size:13px;margin:8px 0;white-space:pre-line}
|
||
.legend{color:#9aa2b1;font-size:12px;margin:4px 0}
|
||
.copybtn{background:#2f5f96;color:#fff;border:0;border-radius:8px;padding:3px 10px;font-size:12px;font-weight:400;cursor:pointer;margin-left:8px;vertical-align:middle}
|
||
.copybtn:hover{background:#3a72b3}
|
||
.cloud{font-size:12px}
|
||
"""
|
||
|
||
|
||
def main() -> int:
|
||
ap = argparse.ArgumentParser()
|
||
ap.add_argument("--snapshot", required=True)
|
||
ap.add_argument("--out", required=True)
|
||
ap.add_argument("--mtgch", default="data/mtgch")
|
||
ap.add_argument("--report-dir", default=None)
|
||
args = ap.parse_args()
|
||
out = Path(args.out)
|
||
snapshot = Path(args.snapshot)
|
||
report_dir = Path(args.report_dir) if args.report_dir else out / "reports/templates"
|
||
build(snapshot, out, Path(args.mtgch), report_dir)
|
||
return 0
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|