Files
mtga/scripts/fetch_17lands_api.py
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

939 lines
38 KiB
Python

#!/usr/bin/env python3
"""Fetch 17Lands *web API* data (as opposed to the bulk public datasets).
Currently implements the trophy-deck pipeline, which is the only way to get
actual 40-card decklists. Reverse-engineered facts (all verified):
* ``GET /api/trophies/?format=<FMT>&expansion=<SET>`` -> up to 500 recent
trophy decks; ``format`` required; pagination/time params are ignored.
* ``POST /api/trophies/`` body
``{expansion, event_type, card_names[], ranks[], deck_colors[]}`` -> up to
100 recent decks. Only ``deck_colors`` actually filters (10 WUBRG pairs,
100 unique each, no overlap). ``card_names`` / ``ranks`` are no-ops.
* ``GET /api/deck/draft/?draft_id=<id>&deck_index=<n>`` -> full decklist as
``data.groups[]{name: Maindeck|Sideboard, cards:[mtga_id, ...]}``.
The union of GET + the 10 color pairs is ~1100 unique decks per poll for a busy
set; because the window rolls, run this periodically and it accumulates.
Examples
--------
# Collect the index only and report counts.
python scripts/fetch_17lands_api.py trophies --set FRA --format PremierDraft --index-only
# Collect index + fetch every 40-card decklist, 6 req/s, 4 workers.
python scripts/fetch_17lands_api.py trophies --set FRA --format PremierDraft -w 4 -r 6
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import threading
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
from pathlib import Path
from urllib.error import HTTPError, URLError
from urllib.parse import quote
from urllib.request import Request, build_opener, ProxyHandler, urlopen
BASE = "https://www.17lands.com"
USER_AGENT = "mtga-17lands-fetcher/1.0"
COLOR_PAIRS = ["WU", "UB", "BR", "RG", "WG", "WB", "BG", "UR", "UG", "WR"]
DEFAULT_OUT = Path(__file__).resolve().parent.parent / "data" / "17lands"
# --------------------------------------------------------------------------- #
# HTTP
# --------------------------------------------------------------------------- #
def http_json(url: str, method: str = "GET", body: dict | None = None,
timeout: float = 60, retries: int = 3) -> dict:
payload = json.dumps(body).encode("utf-8") if body is not None else None
headers = {"User-Agent": USER_AGENT, "Accept": "application/json"}
if payload is not None:
headers["Content-Type"] = "application/json"
last = None
for attempt in range(1, retries + 1):
try:
req = Request(url, data=payload, headers=headers, method=method)
with urlopen(req, timeout=timeout) as resp:
return json.loads(resp.read().decode("utf-8"))
except (HTTPError, URLError, TimeoutError, OSError, json.JSONDecodeError) as exc:
last = exc
if attempt < retries:
time.sleep(min(2 ** attempt, 8))
raise RuntimeError(f"request failed: {url}: {last}")
class RateLimiter:
"""Thread-safe token spacing: at most ``rate`` requests per second."""
def __init__(self, rate: float):
self.interval = 1.0 / rate if rate > 0 else 0.0
self.lock = threading.Lock()
self.next_t = 0.0
def wait(self) -> None:
if not self.interval:
return
with self.lock:
now = time.monotonic()
delay = max(0.0, self.next_t - now)
self.next_t = max(now, self.next_t) + self.interval
if delay:
time.sleep(delay)
# --------------------------------------------------------------------------- #
# Trophy index
# --------------------------------------------------------------------------- #
def _key(entry: dict) -> str:
return f"{entry['aggregate_id']}:{entry['deck_index']}"
def collect_index(expansion: str, fmt: str, limiter: RateLimiter,
quiet: bool = False) -> dict[str, dict]:
"""Union of the 500-item GET and the 10 color-pair POSTs, deduped."""
entries: dict[str, dict] = {}
def add(rows, source):
for row in rows:
k = _key(row)
if k not in entries:
entries[k] = {**row, "source": source}
limiter.wait()
data = http_json(f"{BASE}/api/trophies/?format={fmt}&expansion={expansion}")
add(data.get("data", []), "get")
if not quiet:
print(f" GET -> {len(entries):4} unique", file=sys.stderr)
for color in COLOR_PAIRS:
limiter.wait()
body = {
"expansion": expansion,
"event_type": fmt,
"card_names": [],
"ranks": [],
"deck_colors": [color],
}
data = http_json(f"{BASE}/api/trophies/", method="POST", body=body)
before = len(entries)
add(data.get("data", []), f"post:{color}")
if not quiet:
print(f" POST {color:<2} -> {len(entries):4} unique (+{len(entries) - before})",
file=sys.stderr)
return entries
class ProxyPool:
"""Round-robin-ish proxy pool: stick to the current proxy until it fails
(HTTP 403 / connect error), then rotate to the next one."""
def __init__(self, proxies: list[str]):
self.proxies = proxies
self.lock = threading.Lock()
self.idx = 0
self.dead: set[str] = set()
@property
def has_proxies(self) -> bool:
return bool(self.proxies)
def acquire(self) -> str | None:
with self.lock:
if not self.proxies:
return None
n = len(self.proxies)
if len(self.dead) >= n:
self.dead.clear()
while self.proxies[self.idx % n] in self.dead:
self.idx += 1
return self.proxies[self.idx % n]
def mark_dead(self, proxy: str | None) -> None:
if proxy is None:
return
with self.lock:
self.dead.add(proxy)
self.idx += 1
def load_proxies(args) -> ProxyPool:
items: list[str] = list(getattr(args, "proxy", None) or [])
if getattr(args, "proxy_file", None):
for line in Path(args.proxy_file).read_text(encoding="utf-8").splitlines():
line = line.strip()
if line and not line.startswith("#"):
items.append(line)
for env in ("HTTPS_PROXY", "https_proxy", "HTTP_PROXY", "http_proxy", "ALL_PROXY", "all_proxy"):
value = os.environ.get(env)
if value:
items.append(value)
normalized = [p if "://" in p else "http://" + p for p in items]
return ProxyPool(normalized)
COOKIE = "" # Cookie header value, populated by load_cookies()
def _headers(accept: str = "application/json") -> dict:
headers = {"User-Agent": USER_AGENT, "Accept": accept}
if COOKIE:
headers["Cookie"] = COOKIE
return headers
def load_cookies(args) -> str:
"""Load a Cookie header from --cookie (string) or --cookie-file
(a raw Cookie header line, or a Netscape cookies.txt export)."""
global COOKIE
raw = None
if getattr(args, "cookie", None):
raw = args.cookie
elif getattr(args, "cookie_file", None):
raw = Path(args.cookie_file).read_text(encoding="utf-8")
if not raw:
return COOKIE
raw = raw.strip()
if "\t" in raw: # Netscape cookies.txt
parts = []
for line in raw.splitlines():
line = line.strip()
if not line or line.startswith("#"):
continue
cols = line.split("\t")
if len(cols) >= 7:
parts.append(f"{cols[5]}={cols[6]}")
COOKIE = "; ".join(parts)
else:
if raw.lower().startswith("cookie:"):
raw = raw.split(":", 1)[1]
COOKIE = " ".join(raw.split())
return COOKIE
def _open(url: str, headers: dict, timeout: float, proxy: str | None):
opener = build_opener(ProxyHandler({"http": proxy, "https": proxy})) if proxy else build_opener()
return opener.open(Request(url, headers=headers), timeout=timeout)
def fetch_json_rl(url: str, limiter: RateLimiter, cooldown: "Cooldown",
proxies: ProxyPool | None = None, retries: int = 12,
timeout: float = 60) -> dict:
"""GET a URL as JSON with shared rate-limiting, 403 cooldown and proxy rotation."""
headers = _headers()
proxies = proxies or ProxyPool([])
soft = 0 # non-403 errors count against ``retries``
rl = 0 # 403s are IP-level; the router rotates, so retry freely
while soft < retries and rl < 5000:
if not proxies.has_proxies:
cooldown.wait()
limiter.wait()
proxy = proxies.acquire()
try:
with _open(url, headers, timeout, proxy) as resp:
return json.loads(resp.read().decode("utf-8"))
except HTTPError as exc:
if exc.code == 403:
rl += 1
proxies.mark_dead(proxy)
if not proxies.has_proxies:
cooldown.hit()
continue
if exc.code == 404: # permanent: resource does not exist
raise
soft += 1
if soft >= retries:
raise
time.sleep(min(2 ** soft, 8))
except (URLError, TimeoutError, OSError, json.JSONDecodeError):
soft += 1
proxies.mark_dead(proxy)
if soft >= retries:
raise
time.sleep(min(2 ** soft, 5))
raise RuntimeError("exhausted retries")
def fetch_bytes_rl(url: str, limiter: RateLimiter, cooldown: "Cooldown",
proxies: ProxyPool | None = None, retries: int = 12,
timeout: float = 120) -> bytes:
"""GET a URL as raw bytes (e.g. a gzipped replay) with the same resilience."""
headers = _headers(accept="application/octet-stream")
proxies = proxies or ProxyPool([])
soft = 0
rl = 0
while soft < retries and rl < 5000:
if not proxies.has_proxies:
cooldown.wait()
limiter.wait()
proxy = proxies.acquire()
try:
with _open(url, headers, timeout, proxy) as resp:
return resp.read()
except HTTPError as exc:
if exc.code == 403:
rl += 1
proxies.mark_dead(proxy)
if not proxies.has_proxies:
cooldown.hit()
continue
if exc.code == 404: # permanent: resource does not exist
raise
soft += 1
if soft >= retries:
raise
time.sleep(min(2 ** soft, 8))
except (URLError, TimeoutError, OSError):
soft += 1
proxies.mark_dead(proxy)
if soft >= retries:
raise
time.sleep(min(2 ** soft, 5))
raise RuntimeError("exhausted retries")
def fetch_deck(aggregate_id: str, deck_index: int, limiter: RateLimiter,
cooldown: "Cooldown", proxies: ProxyPool | None = None,
retries: int = 12, timeout: float = 60) -> tuple[list[int], list[int]]:
url = f"{BASE}/api/deck/draft/?draft_id={aggregate_id}&deck_index={deck_index}"
data = fetch_json_rl(url, limiter, cooldown, proxies, retries, timeout)
maindeck: list[int] = []
sideboard: list[int] = []
for group in data.get("data", {}).get("groups", []):
if group.get("name") == "Maindeck":
maindeck = group.get("cards", [])
elif group.get("name") == "Sideboard":
sideboard = group.get("cards", [])
return maindeck, sideboard
class Cooldown:
"""Global pause shared by all workers when the server rate-limits us (HTTP 403)."""
def __init__(self, seconds: float):
self.seconds = seconds
self.until = 0.0
self.lock = threading.Lock()
def hit(self) -> None:
with self.lock:
self.until = max(self.until, time.monotonic() + self.seconds)
def wait(self) -> None:
while True:
with self.lock:
remaining = self.until - time.monotonic()
if remaining <= 0:
return
print(f" [cooldown] rate-limited; waiting {remaining:.0f}s", file=sys.stderr)
time.sleep(min(remaining, 10))
# --------------------------------------------------------------------------- #
# Files
# --------------------------------------------------------------------------- #
def read_done_keys(path: Path) -> set[str]:
done: set[str] = set()
if not path.exists():
return done
with path.open(encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
row = json.loads(line)
done.add(f"{row['aggregate_id']}:{row['deck_index']}")
except (json.JSONDecodeError, KeyError):
continue
return done
def write_jsonl(path: Path, rows: list[dict]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
with path.open("w", encoding="utf-8") as fh:
for row in rows:
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
def load_card_names(expansion: str, fmt: str, limiter: RateLimiter) -> dict[int, str]:
limiter.wait()
data = http_json(
f"{BASE}/api/card_data?expansion={expansion}&event_type={fmt}&time_period=ALL_TIME"
)
return {c["mtga_id"]: c["name"] for c in data.get("data", []) if "mtga_id" in c}
# --------------------------------------------------------------------------- #
# Command: trophies
# --------------------------------------------------------------------------- #
def cmd_trophies(args) -> int:
if args.out:
out_dir = Path(args.out)
else:
stamp = datetime.now().strftime("%Y%m%d")
out_dir = DEFAULT_OUT / f"{args.set.upper()}{stamp}" / "trophies"
index_path = out_dir / "trophies_index.jsonl"
decks_path = out_dir / "trophies_decks.jsonl"
cards_path = out_dir / "cards.json"
out_dir.mkdir(parents=True, exist_ok=True)
limiter = RateLimiter(args.rate)
cooldown = Cooldown(args.cooldown)
proxies = load_proxies(args)
if proxies.has_proxies:
print(f"[proxies] {len(proxies.proxies)} proxies loaded (rotate on 403)", file=sys.stderr)
t0 = time.time()
# ---- index ----
if args.reuse_index and index_path.exists():
entries = {}
with index_path.open(encoding="utf-8") as fh:
for line in fh:
row = json.loads(line)
entries[_key(row)] = row
print(f"[index] reused {len(entries)} entries from {index_path}", file=sys.stderr)
else:
print(f"[index] collecting trophy index for {args.set} {args.format} ...", file=sys.stderr)
entries = collect_index(args.set.upper(), args.format, limiter, quiet=args.quiet)
write_jsonl(index_path, list(entries.values()))
print(f"[index] {len(entries)} unique entries -> {index_path}", file=sys.stderr)
if args.index_only:
_summary_index(entries)
return 0
# ---- card names ----
names: dict[int, str] = {}
if cards_path.exists():
names = {int(k): v for k, v in json.loads(cards_path.read_text(encoding="utf-8")).items()}
else:
names = load_card_names(args.set.upper(), args.format, limiter)
cards_path.write_text(json.dumps(names, ensure_ascii=False, indent=0), encoding="utf-8")
print(f"[cards] {len(names)} card names", file=sys.stderr)
# ---- decklists ----
done = read_done_keys(decks_path)
todo = [e for k, e in entries.items() if k not in done]
if args.max_decks:
todo = todo[: args.max_decks]
print(f"[decks] {len(done)} already done, {len(todo)} to fetch", file=sys.stderr)
lock = threading.Lock()
stats = {"fetched": 0, "valid": 0, "invalid": 0, "failed": 0}
started = time.time()
def worker(entry: dict) -> dict | None:
try:
maindeck, sideboard = fetch_deck(entry["aggregate_id"], entry["deck_index"],
limiter, cooldown, proxies)
valid = len(maindeck) >= 40 # limited decks are 40+ cards (41, 42, ... are legal)
if not valid:
with lock:
stats["invalid"] += 1
return None
row = {
"aggregate_id": entry["aggregate_id"],
"deck_index": entry["deck_index"],
"colors": entry.get("colors"),
"wins": entry.get("wins"),
"losses": entry.get("losses"),
"start_rank": entry.get("start_rank"),
"end_rank": entry.get("end_rank"),
"time": entry.get("time"),
"source": entry.get("source"),
"maindeck": _counts(maindeck, names),
"sideboard": _counts(sideboard, names),
"fetched_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
}
return row
except Exception as exc: # noqa: BLE001
with lock:
stats["failed"] += 1
print(f" [failed] {_key(entry)}: {exc}", file=sys.stderr)
return None
mode = "a" if decks_path.exists() else "w"
with decks_path.open(mode, encoding="utf-8") as fh, \
ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = [pool.submit(worker, e) for e in todo]
for i, fut in enumerate(as_completed(futures), 1):
row = fut.result()
if row is not None:
with lock:
stats["valid"] += 1
fh.write(json.dumps(row, ensure_ascii=False) + "\n")
fh.flush()
with lock:
stats["fetched"] += 1
if not args.quiet and (i % 25 == 0 or i == len(futures)):
elapsed = time.time() - started
rate = i / elapsed if elapsed else 0
print(f" {i}/{len(futures)} valid={stats['valid']} invalid={stats['invalid']} "
f"failed={stats['failed']} {rate:.1f}/s", file=sys.stderr)
total_valid = len(read_done_keys(decks_path))
print("\n===== trophy fetch summary =====")
print(f"index entries : {len(entries)}")
print(f"new decks fetched : {stats['fetched']}")
print(f" valid (>=40 cards): {stats['valid']}")
print(f" invalid : {stats['invalid']}")
print(f" failed : {stats['failed']}")
print(f"total valid stored : {total_valid} -> {decks_path}")
print(f"elapsed : {time.time() - t0:.1f}s")
return 0
def cmd_draftdata(args) -> int:
"""Fetch full per-pick draft replays (`/data/draft?draft_id=`) incl. pack contents."""
stamp = datetime.now().strftime("%Y%m%d")
out_dir = Path(args.out) if args.out else (DEFAULT_OUT / f"{args.set.upper()}{stamp}" / "draftdata")
out_dir.mkdir(parents=True, exist_ok=True)
ids: list[str] = []
seen: set[str] = set()
with Path(args.index).open(encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
did = json.loads(line)["aggregate_id"]
if did not in seen:
seen.add(did)
ids.append(did)
done = {p.stem for p in out_dir.glob("*.json")}
pending = [d for d in ids if d not in done]
if args.max_drafts:
pending = pending[: args.max_drafts]
limiter = RateLimiter(args.rate)
cooldown = Cooldown(args.cooldown)
proxies = load_proxies(args)
print(f"[draftdata] {len(ids)} ids, {len(done)} done, {len(pending)} pending", file=sys.stderr)
lock = threading.Lock()
stats = {"ok": 0, "failed": 0, "missing": 0}
missing: list[str] = []
t0 = time.time()
def worker(did: str) -> None:
try:
data = fetch_json_rl(f"{BASE}/data/draft?draft_id={did}", limiter, cooldown, proxies)
tmp = out_dir / f"{did}.json.part"
tmp.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
tmp.replace(out_dir / f"{did}.json")
with lock:
stats["ok"] += 1
except HTTPError as exc:
if exc.code == 404: # this draft has no pick replay
with lock:
missing.append(did)
stats["missing"] += 1
return
with lock:
stats["failed"] += 1
print(f" [failed] {did}: {exc}", file=sys.stderr)
except Exception as exc: # noqa: BLE001
with lock:
stats["failed"] += 1
print(f" [failed] {did}: {exc}", file=sys.stderr)
with ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = [pool.submit(worker, d) for d in pending]
for i, fut in enumerate(as_completed(futures), 1):
fut.result()
if not args.quiet and (i % 10 == 0 or i == len(futures)):
el = time.time() - t0
print(f" {i}/{len(futures)} ok={stats['ok']} missing={stats['missing']} "
f"failed={stats['failed']} {i / el if el else 0:.1f}/s", file=sys.stderr)
if missing:
(out_dir / "_missing.txt").write_text("\n".join(sorted(missing)) + "\n", encoding="utf-8")
print(f"\n===== draftdata summary =====\nnew: {stats['ok']} missing(404): {stats['missing']} "
f"failed: {stats['failed']} stored: {len(done) + stats['ok']}\n-> {out_dir}")
return 0
def cmd_replays(args) -> int:
"""Download the turn-by-turn GRE replay (gzip) for every game.
``history_path`` is derived from ``game_results[].history_s3_path``
(``s3://17lands-game-histories/<rel>.json.gz`` -> ``<rel>``), so no extra
request to /data/history_info/ is needed.
"""
if not COOKIE:
print("[replays] WARNING: no cookie given; /data/history requires login.", file=sys.stderr)
out_dir = Path(args.out) if args.out else (
DEFAULT_OUT / f"{args.set.upper()}{datetime.now():%Y%m%d}" / "replays")
out_dir.mkdir(parents=True, exist_ok=True)
index_path = out_dir / "replay_index.jsonl"
games: list[dict] = []
seen: set[str] = set()
with Path(args.events).open(encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
rec = json.loads(line)
did = rec["draft_id"]
for mi, match in enumerate(rec.get("details", {}).get("match_results") or []):
for gi, game in enumerate(match.get("game_results") or []):
hp = game.get("history_s3_path")
if not hp:
continue
rel = hp.split("17lands-game-histories/", 1)[-1]
if rel.endswith(".json.gz"):
rel = rel[: -len(".json.gz")]
if rel in seen:
continue
seen.add(rel)
games.append({
"history_path": rel, "draft_id": did,
"match_index": mi, "game_index": gi,
"won": game.get("won"), "on_play": game.get("on_play"),
"opponent_colors": game.get("opponent_colors"),
"total_turns": game.get("total_turns"),
"game_number": game.get("game_number"),
})
with index_path.open("w", encoding="utf-8") as fh:
for g in games:
fh.write(json.dumps(g, ensure_ascii=False) + "\n")
if args.selection_file:
want = [ln.strip() for ln in Path(args.selection_file).read_text(encoding="utf-8").splitlines()
if ln.strip()]
order = {hp: i for i, hp in enumerate(want)}
games = [g for g in games if g["history_path"] in order]
games.sort(key=lambda g: order[g["history_path"]])
done = {p.relative_to(out_dir).as_posix()[: -len(".json.gz")] for p in out_dir.rglob("*.json.gz")}
pending = [g for g in games if g["history_path"] not in done]
if args.max_replays:
pending = pending[: args.max_replays]
limiter = RateLimiter(args.rate)
cooldown = Cooldown(args.cooldown)
proxies = load_proxies(args)
print(f"[replays] {len(games)} games, {len(done)} done, {len(pending)} pending", file=sys.stderr)
lock = threading.Lock()
stats = {"ok": 0, "failed": 0}
t0 = time.time()
def worker(g: dict) -> None:
rel = g["history_path"]
dest = out_dir / (rel + ".json.gz")
dest.parent.mkdir(parents=True, exist_ok=True)
try:
data = fetch_bytes_rl(
f"{BASE}/data/history?history_path={quote(rel, safe='')}",
limiter, cooldown, proxies)
tmp = dest.with_suffix(".part")
tmp.write_bytes(data)
tmp.replace(dest)
with lock:
stats["ok"] += 1
except Exception as exc: # noqa: BLE001
with lock:
stats["failed"] += 1
print(f" [failed] {rel}: {exc}", file=sys.stderr)
with ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = [pool.submit(worker, g) for g in pending]
for i, fut in enumerate(as_completed(futures), 1):
fut.result()
if not args.quiet and (i % 200 == 0 or i == len(futures)):
el = time.time() - t0
print(f" {i}/{len(futures)} ok={stats['ok']} failed={stats['failed']} "
f"{i / el if el else 0:.1f}/s", file=sys.stderr)
print("\n===== replays summary =====")
print(f"games : {len(games)}")
print(f"new replays : {stats['ok']}")
print(f"failed : {stats['failed']}")
print(f"stored : {len(done) + stats['ok']} -> {out_dir}")
print(f"elapsed : {time.time() - t0:.1f}s")
return 0
def cmd_stats(args) -> int:
"""Fetch the aggregate/statistics endpoints (scenarios 1, 2, 6).
* /api/card_data -> card_data.json (per-card)
* /api/card_data?colors=<pair> -> card_data.<pair>.json (archetype context)
* /color_ratings/data -> color_ratings.json (color win rates)
* /api/draft_metagame/ -> draft_metagame.json (pick order over time)
"""
stamp = datetime.now().strftime("%Y%m%d")
out_dir = Path(args.out) if args.out else (DEFAULT_OUT / f"{args.set.upper()}{stamp}" / "stats")
out_dir.mkdir(parents=True, exist_ok=True)
limiter = RateLimiter(args.rate)
cooldown = Cooldown(args.cooldown)
proxies = load_proxies(args)
exp, fmt = args.set.upper(), args.format
base = f"{BASE}/api/card_data?expansion={exp}&event_type={fmt}&time_period={args.time_period}"
jobs = [("card_data.json", base)]
for color in COLOR_PAIRS:
jobs.append((f"card_data.{color}.json", f"{base}&colors={color}"))
jobs.append(("color_ratings.json",
f"{BASE}/color_ratings/data?expansion={exp}&event_type={fmt}"
f"&time_period={args.time_period}&combine_splash=true"))
jobs.append(("draft_metagame.json",
f"{BASE}/api/draft_metagame/?expansion={exp}&format={fmt}"
f"&time_period={args.time_period}"))
for name, url in jobs:
try:
data = fetch_json_rl(url, limiter, cooldown, proxies)
(out_dir / name).write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
n = len(data.get("data", [])) if isinstance(data, dict) else len(data)
print(f" [ok] {name:26} ({n} items)", file=sys.stderr)
except Exception as exc: # noqa: BLE001
print(f" [failed] {name}: {exc}", file=sys.stderr)
print(f"\nstored -> {out_dir}")
return 0
def read_jsonl_ids(path: Path, key: str) -> set:
ids: set = set()
if not path.exists():
return ids
with path.open(encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
try:
ids.add(json.loads(line)[key])
except (json.JSONDecodeError, KeyError):
continue
return ids
def cmd_drafts(args) -> int:
"""Per trophy draft: /api/draft_picks + /data/event_details (game results)."""
if args.out:
out_dir = Path(args.out)
else:
stamp = datetime.now().strftime("%Y%m%d")
out_dir = DEFAULT_OUT / f"{args.set.upper()}{stamp}" / "drafts"
out_dir.mkdir(parents=True, exist_ok=True)
ids: list[str] = []
seen: set[str] = set()
with Path(args.index).open(encoding="utf-8") as fh:
for line in fh:
line = line.strip()
if not line:
continue
did = json.loads(line)["aggregate_id"]
if did not in seen:
seen.add(did)
ids.append(did)
picks_path = out_dir / "draft_picks.jsonl"
events_path = out_dir / "event_details.jsonl"
have_picks = read_jsonl_ids(picks_path, "draft_id")
have_events = read_jsonl_ids(events_path, "draft_id")
total = len(ids)
pending = [d for d in ids if d not in have_picks or d not in have_events]
if args.max_drafts:
pending = pending[: args.max_drafts]
ids = pending
limiter = RateLimiter(args.rate)
cooldown = Cooldown(args.cooldown)
proxies = load_proxies(args)
if proxies.has_proxies:
print(f"[proxies] {len(proxies.proxies)} proxies loaded", file=sys.stderr)
print(f"[drafts] {total} total, {len(ids)} pending "
f"(picks done={len(have_picks)} events done={len(have_events)})", file=sys.stderr)
lock = threading.Lock()
stats = {"picks": 0, "events": 0, "failed": 0, "done": 0}
t0 = time.time()
with picks_path.open("a", encoding="utf-8") as pf, \
events_path.open("a", encoding="utf-8") as ef:
def worker(did: str) -> None:
got: dict[str, dict] = {}
try:
if did not in have_picks:
got["picks"] = fetch_json_rl(
f"{BASE}/api/draft_picks?draft_id={did}", limiter, cooldown, proxies)
if did not in have_events:
got["events"] = fetch_json_rl(
f"{BASE}/data/event_details?draft_id={did}", limiter, cooldown, proxies)
except Exception as exc: # noqa: BLE001
with lock:
stats["failed"] += 1
print(f" [failed] {did}: {exc}", file=sys.stderr)
return
with lock:
if "picks" in got:
pf.write(json.dumps({"draft_id": did, **got["picks"]}, ensure_ascii=False) + "\n")
pf.flush()
stats["picks"] += 1
if "events" in got:
ef.write(json.dumps({"draft_id": did, **got["events"]}, ensure_ascii=False) + "\n")
ef.flush()
stats["events"] += 1
stats["done"] += 1
with ThreadPoolExecutor(max_workers=args.workers) as pool:
futures = [pool.submit(worker, did) for did in ids]
for i, fut in enumerate(as_completed(futures), 1):
fut.result()
if not args.quiet and (i % 50 == 0 or i == len(futures)):
elapsed = time.time() - t0
rate = i / elapsed if elapsed else 0
print(f" {i}/{len(futures)} picks={stats['picks']} events={stats['events']} "
f"failed={stats['failed']} {rate:.1f}/s", file=sys.stderr)
print("\n===== drafts summary =====")
print(f"drafts : {len(ids)}")
print(f"picks new : {stats['picks']} (total {len(read_jsonl_ids(picks_path, 'draft_id'))})")
print(f"events new : {stats['events']} (total {len(read_jsonl_ids(events_path, 'draft_id'))})")
print(f"failed : {stats['failed']}")
print(f"elapsed : {time.time() - t0:.1f}s")
return 0
def _counts(cards: list[int], names: dict[int, str]) -> list[dict]:
from collections import Counter
counter = Counter(cards)
return [
{"mtga_id": cid, "name": names.get(cid, str(cid)), "count": n}
for cid, n in sorted(counter.items(), key=lambda kv: (-kv[1], kv[0]))
]
def _summary_index(entries: dict[str, dict]) -> None:
from collections import Counter
print("\n===== index summary =====")
print(f"unique decks : {len(entries)}")
print("by source :", dict(Counter(e["source"] for e in entries.values()).most_common()))
print("by colors :", Counter(e.get("colors") for e in entries.values()).most_common(12))
# --------------------------------------------------------------------------- #
# CLI
# --------------------------------------------------------------------------- #
def build_parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
description="Fetch 17Lands web-API data (trophy decks).",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog=__doc__,
)
sub = parser.add_subparsers(dest="command")
p = sub.add_parser("trophies", help="collect trophy-deck index + full decklists")
p.add_argument("--set", required=True, help="expansion code, e.g. FRA")
p.add_argument("--format", default="PremierDraft", help="event type / format (default: PremierDraft)")
p.add_argument("--out", default=None,
help="output directory (default: data/17lands/<SET><YYYYMMDD>/trophies)")
p.add_argument("-w", "--workers", type=int, default=4, help="parallel deck fetches (default: 4)")
p.add_argument("-r", "--rate", type=float, default=5.0, help="max requests/sec (default: 5)")
p.add_argument("--cooldown", type=float, default=120.0,
help="global pause in seconds after an HTTP 403 when no proxies are set (default: 120)")
p.add_argument("--proxy", action="append", default=[], metavar="URL",
help="proxy URL, repeatable (e.g. http://user:pass@host:port)")
p.add_argument("--proxy-file", metavar="FILE",
help="file with one proxy per line; rotate to the next on HTTP 403")
p.add_argument("--cookie", help="Cookie header value (or use --cookie-file)")
p.add_argument("--cookie-file", help="file with a Cookie header or Netscape cookies.txt")
p.add_argument("--index-only", action="store_true", help="only collect the index, no decklists")
p.add_argument("--reuse-index", action="store_true", help="reuse existing trophies_index.jsonl")
p.add_argument("--max-decks", type=int, help="limit decklists fetched (for testing)")
p.add_argument("-q", "--quiet", action="store_true")
p.set_defaults(func=cmd_trophies)
pd = sub.add_parser("drafts", help="fetch draft picks + event/game details per trophy draft")
pd.add_argument("--set", required=True)
pd.add_argument("--format", default="PremierDraft")
pd.add_argument("--index", required=True, help="trophies_index.jsonl from the trophies command")
pd.add_argument("--out", default=None, help="output dir (default: data/17lands/<SET><YYYYMMDD>/drafts)")
pd.add_argument("-w", "--workers", type=int, default=8)
pd.add_argument("-r", "--rate", type=float, default=10.0)
pd.add_argument("--cooldown", type=float, default=2.0)
pd.add_argument("--proxy", action="append", default=[])
pd.add_argument("--proxy-file")
pd.add_argument("--cookie")
pd.add_argument("--cookie-file")
pd.add_argument("--max-drafts", type=int)
pd.add_argument("-q", "--quiet", action="store_true")
pd.set_defaults(func=cmd_drafts)
pr = sub.add_parser("replays", help="download turn-by-turn GRE replays (login required)")
pr.add_argument("--set", required=True)
pr.add_argument("--format", default="PremierDraft")
pr.add_argument("--events", required=True, help="event_details.jsonl from the drafts command")
pr.add_argument("--selection-file", default=None,
help="only fetch the history_paths listed in this file (one per line)")
pr.add_argument("--out", default=None, help="output dir (default: data/17lands/<SET><YYYYMMDD>/replays)")
pr.add_argument("-w", "--workers", type=int, default=8)
pr.add_argument("-r", "--rate", type=float, default=10.0)
pr.add_argument("--cooldown", type=float, default=2.0)
pr.add_argument("--proxy", action="append", default=[])
pr.add_argument("--proxy-file")
pr.add_argument("--cookie")
pr.add_argument("--cookie-file")
pr.add_argument("--max-replays", type=int)
pr.add_argument("-q", "--quiet", action="store_true")
pr.set_defaults(func=cmd_replays)
ps = sub.add_parser("stats", help="fetch aggregate stats: card_data, per-color, color_ratings, draft_metagame")
ps.add_argument("--set", required=True)
ps.add_argument("--format", default="PremierDraft")
ps.add_argument("--time-period", default="ALL_TIME")
ps.add_argument("--out", default=None, help="output dir (default: data/17lands/<SET><YYYYMMDD>/stats)")
ps.add_argument("-r", "--rate", type=float, default=5.0)
ps.add_argument("--cooldown", type=float, default=2.0)
ps.add_argument("--proxy", action="append", default=[])
ps.add_argument("--proxy-file")
ps.add_argument("--cookie")
ps.add_argument("--cookie-file")
ps.set_defaults(func=cmd_stats)
pdd = sub.add_parser("draftdata", help="fetch full per-pick draft replays incl. pack contents")
pdd.add_argument("--set", required=True)
pdd.add_argument("--format", default="PremierDraft")
pdd.add_argument("--index", required=True, help="trophies_index.jsonl (draft ids)")
pdd.add_argument("--out", default=None,
help="output dir (default: data/17lands/<SET><YYYYMMDD>/draftdata)")
pdd.add_argument("-w", "--workers", type=int, default=48)
pdd.add_argument("-r", "--rate", type=float, default=0.0, help="requests/sec (0 = no limit)")
pdd.add_argument("--cooldown", type=float, default=0.0)
pdd.add_argument("--proxy", action="append", default=[])
pdd.add_argument("--proxy-file")
pdd.add_argument("--cookie")
pdd.add_argument("--cookie-file")
pdd.add_argument("--max-drafts", type=int)
pdd.add_argument("-q", "--quiet", action="store_true")
pdd.set_defaults(func=cmd_draftdata)
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
if not getattr(args, "func", None):
parser.print_help()
return 2
load_cookies(args)
return args.func(args)
if __name__ == "__main__":
try:
raise SystemExit(main())
except KeyboardInterrupt:
print("\nInterrupted.", file=sys.stderr)
raise SystemExit(130)