#!/usr/bin/env python3 """Render the archetype templates as an HTML view. Combines: value//templates/*.json (parameters + evidence) value//templates/_members.json (cluster -> draft ids) data/17lands//drafts/event_details.jsonl (game results) data/mtgch/image-en|image-cn/*.webp (card art, EN/CN) Output: value//reports/templates/index.html + .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//.) 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'{esc(lab)}') off += dash return (f'' f'{"".join(segs)}') 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'{esc(txt)}' 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'{esc(name)}' if cn: imgs += f'{esc(name)}' if not en and not cn: imgs = '
no image
' badge = f'
×{count}
' if count > 1 else '' return (f'
{imgs}{badge}
' f'
{esc(name)}
') 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"{esc(t)}" 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'{esc(c[' if cn: imgs += f'{esc(c[' if not en and not cn: imgs = '
no image
' cid = c.get("mtga_id") cn = cn_names.get(c["name"]) rarity = (c.get("rarity") or "").lower() badge = f'
×{deck_count}
' 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"""
{imgs}{badge}
IIH {_metric_html("iih", _IIH.get(c.get("name")))} / ALSA {_metric_html("alsa", c.get("alsa"))}
{esc(c["name"])}
{cw:.2f} {pct(inc_v)}/{use_part}
Δ {cd_s} · signal {c.get("signal") if c.get("signal") is not None else "—"} · prio {c.get("pick_priority")} · n={c.get("cluster_sample_games")}
{tags}
{f'
syn: {syn}
' if syn else ''}
{roles}
""" 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"{esc(label)}" # not a known card -> plain text rr = (c.get("rarity") or "common").lower() return (f'{esc(label)}') def _md_inline(s, img, cdata): """[[Card Name]] -> clickable card tag; **bold** -> .""" 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("" + esc(s[j + 2: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("

" + _md_inline(para, img, cdata) + "

") return "".join(out) def desc_html(t): import re as _re return _re.sub(r"\*\*(.+?)\*\*", r"\1", 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'
' f'
{k}
{v:.1f}
' 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'
' f'
' f'
{esc(k)}
{wr*100:.0f}%
') # 只显示对手「双色」对位(单色/未分类不显示) _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 = ("

信号牌(看到就进这个思路)

\n
%s
" % 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'
{_tiles}
' else: ref_html = '

(未生成典型套牌)

' # 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'×{_c}' if _c > 1 else "" _parts.append(f'{esc(_nm)}{_badge}') 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'
' f'{esc(info["rec"])}{esc(info["colors"])}' f'{sum(c for _, c in info["cards"])} 张{mine}' f'⧉ 复制
' f'
{mini}
') decks_html = (f'

簇内牌表({len(deck_ids)} 副)

{"".join(rows)}
' if rows else '

簇内牌表

(无)

') guide_html = ('

攻略

' + render_guide(t.get("guide_zh"), img, cdata or {}) + '
') if t.get("guide_zh") else "" beh_html = ('

实战数据(replay)

' + render_guide(t.get("behavior_zh"), img, cdata or {}) + '
') if t.get("behavior_zh") else "" land_tiles = "".join(card_tile(c, img, id2name, cn_names) for c in lands) doc = f""" {esc(t['archetype_name'])} · {SET} {_banner('')}

{esc(t['archetype_name'])}

archetype {esc(t.get('colors') or t['archetype'])} · slug {esc(slug)} · 核心牌表 {t['n_decks']} / 簇 {t.get('cluster_size', '-')} 副 · {g['n']} 局 · confidence {t['confidence']} · silhouette {t.get('silhouette', '-')}

{desc_html(t)}

{guide_html} {beh_html}
地{dp['land_count']}
生物比{dp['creature_ratio']*100:.0f}%
单局胜率{g['wr']*100:.1f}%
先手胜率{g['op_wr']*100:.1f}%
后手胜率{g['df_wr']*100:.1f}%
平均回合{g['avg_turns']/2:.1f}
平均调度{g['mull']:.2f}
{curve_html}
每根柱 = 该思路核心牌表的平均张数(费用 1/2/3/4/5/6+,共 23 张咒语); advisor 配牌时以 2 / 7 / 6 / 4 / 3 / 1 的完美基线打底、再按这条均值浮动。
{cw_donut}颜色
{bl_donut}基本地
对位胜率 vs 对手双色(绿=高于50%)
{mu_cols}

定义牌

{key_html}
{aff_section}

典型套牌

{ref_html}

生物

{tiles_c}

咒语 / 其他

{tiles_s}

非基本地

{land_tiles}
{decks_html}
{_footbanner(DETAIL_LEGEND)}
""" (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'' f'{esc(t["archetype_name"])}' f'{t["n_decks"]}' f'{t.get("cluster_size", "-")}' f'{dp["creature_ratio"]*100:.0f}%' f'{g["wr"]*100:.1f}%' f'{esc(_pair)} {_p17}' f'{turns_rounds:.1f}' f'{desc_html(t)}') doc = f""" {SET} 模板视图 {_banner()}

{SET} PremierDraft · 子流派模板视图

{rows}
archetype核心数簇数 生物比胜率17lands色组回合打法
{_footbanner('胜率 = 本奖杯样本(偏高);17lands色组 = 该双色在 17lands 全场的胜率')} """ (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 = '已复制 ✓'; 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 ('') _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 = "
".join("%s = %s" % (k, v) for k, v in _DETAIL_LEGEND_ITEMS) def _footbanner(extra: str = "") -> str: return f'' 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())